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/1/0x6C32D8DC35A4063E0AD3AAC756111e462eA38D27/sources/contracts/periphery/utils/AvailableRootsRegistry.sol
* @dev Unregister a root for an attester @param attester Attester which will no longer have the root available @param root Root to unregister/
function unregisterRootForAttester(address attester, uint256 root) external onlyOwner { if (attester == address(0)) revert CannotUnregisterForZeroAddress(); _unregisterRootForAttester(attester, root); }
3,849,619
[ 1, 30076, 279, 1365, 364, 392, 622, 1078, 387, 225, 622, 1078, 387, 6020, 7654, 1492, 903, 1158, 7144, 1240, 326, 1365, 2319, 225, 1365, 7450, 358, 10232, 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, 225, 445, 10232, 2375, 1290, 3075, 7654, 12, 2867, 622, 1078, 387, 16, 2254, 5034, 1365, 13, 3903, 1338, 5541, 288, 203, 565, 309, 261, 270, 1078, 387, 422, 1758, 12, 20, 3719, 15226, 14143, 30076, 1290, 7170, 1887, 5621, 203, 565, 389, 318, 4861, 2375, 1290, 3075, 7654, 12, 270, 1078, 387, 16, 1365, 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 ]
./partial_match/3/0xb49b45457f0B2472B85c3c504a095Ba37C0A9fa5/sources/CousinCoin.sol
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "CousinCoin"; symbol = "CUH"; decimals = 18; _totalSupply = 1000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
5,231,581
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 39, 1481, 267, 27055, 14432, 203, 3639, 3273, 273, 315, 16001, 44, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 9449, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xD4590A43DbcBEF5DBfE3C80cc8d37e574d512B1A/sources/contracts/transferVesting.sol
* @dev Sends the swap and liquify flag to the provided value. If set to `false` tokens collected in the contract will NOT be converted into liquidity./
function setSwapAndLiquifyEnabled(bool enabled) external onlyManager { swapAndLiquifyEnabled = enabled; emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled); }
9,503,789
[ 1, 10501, 326, 7720, 471, 4501, 372, 1164, 2982, 358, 326, 2112, 460, 18, 971, 444, 358, 1375, 5743, 68, 2430, 12230, 316, 326, 6835, 903, 4269, 506, 5970, 1368, 4501, 372, 24237, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 12521, 1876, 48, 18988, 1164, 1526, 12, 6430, 3696, 13, 3903, 1338, 1318, 288, 203, 3639, 7720, 1876, 48, 18988, 1164, 1526, 273, 3696, 31, 203, 3639, 3626, 12738, 1876, 48, 18988, 1164, 1526, 7381, 12, 22270, 1876, 48, 18988, 1164, 1526, 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 ]
./full_match/1/0xc258fF338322b6852C281936D4EdEff8AdfF23eE/sources/src/sgReceiver.sol
sgReceive will receive sgETH and then mint unshETH and send the unshETH back to the original senderExtract the mint information
function sgReceive(uint16 _chainId, bytes memory /*_srcAddress*/, uint /*_nonce*/, address _token, uint amountLD, bytes memory _payload) override external { require(msg.sender == address(stargateRouterAddress), "only stargate router can call sgReceive!"); require(unsheth_gas_cost <= address(this).balance, 'unsheth_gas_cost must be less than the eth balance in this contract'); require(_token == sgethAddress, "only sgeth is supported"); (address userAddress, uint256 min_amount_unshethZap, uint256 unsheth_path) = abi.decode(_payload, (address, uint256, uint256)); if(sgethChainIds[_chainId]){ require(amountLD <= IERC20(sgethAddress).balanceOf(address(this)), "Amount to retry with exceeds contract balance"); uint256 unshethMinted = _mint_unsheth_with_sgeth(amountLD, min_amount_unshethZap, unsheth_path); _bridge_unsheth(_chainId, unshethMinted, unsheth_gas_cost, userAddress); } else{ revert("ChainId not supported"); } }
4,833,427
[ 1, 1055, 11323, 903, 6798, 11150, 1584, 44, 471, 1508, 312, 474, 640, 674, 1584, 44, 471, 1366, 326, 640, 674, 1584, 44, 1473, 358, 326, 2282, 5793, 4976, 326, 312, 474, 1779, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11150, 11323, 12, 11890, 2313, 389, 5639, 548, 16, 1731, 3778, 1748, 67, 4816, 1887, 5549, 16, 2254, 1748, 67, 12824, 5549, 16, 1758, 389, 2316, 16, 2254, 3844, 12069, 16, 1731, 3778, 389, 7648, 13, 3849, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 334, 3175, 340, 8259, 1887, 3631, 315, 3700, 384, 3175, 340, 4633, 848, 745, 11150, 11323, 4442, 1769, 203, 3639, 2583, 12, 318, 674, 546, 67, 31604, 67, 12398, 1648, 1758, 12, 2211, 2934, 12296, 16, 296, 318, 674, 546, 67, 31604, 67, 12398, 1297, 506, 5242, 2353, 326, 13750, 11013, 316, 333, 6835, 8284, 203, 3639, 2583, 24899, 2316, 422, 11150, 546, 1887, 16, 315, 3700, 11150, 546, 353, 3260, 8863, 203, 3639, 261, 2867, 729, 1887, 16, 2254, 5034, 1131, 67, 8949, 67, 318, 674, 546, 62, 438, 16, 2254, 5034, 640, 674, 546, 67, 803, 13, 273, 24126, 18, 3922, 24899, 7648, 16, 261, 2867, 16, 2254, 5034, 16, 2254, 5034, 10019, 203, 203, 3639, 309, 12, 1055, 546, 3893, 2673, 63, 67, 5639, 548, 5717, 95, 203, 5411, 2583, 12, 8949, 12069, 1648, 467, 654, 39, 3462, 12, 1055, 546, 1887, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 315, 6275, 358, 3300, 598, 14399, 6835, 11013, 8863, 203, 5411, 2254, 5034, 640, 674, 546, 49, 474, 329, 273, 389, 81, 474, 67, 318, 674, 546, 67, 1918, 67, 1055, 546, 12, 8949, 12069, 16, 1131, 67, 8949, 67, 318, 674, 546, 62, 438, 16, 640, 674, 546, 2 ]
pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } contract MetaMind is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Meta Mind";// string private constant _symbol = "MIND";// uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; //Buy Fee uint256 private _redisFeeOnBuy = 1;// uint256 private _taxFeeOnBuy = 11;// //Sell Fee uint256 private _redisFeeOnSell = 1;// uint256 private _taxFeeOnSell = 11;// //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xBCBcD51C71C1912C3ca2aCA3B5e6589c52e5c168);// address payable private _marketingAddress = payable(0x30bB49874679540bf905bA1fC9F1baf2718D1316);// IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 25000000 * 10**9; // uint256 public _maxWalletSize = 150000000 * 10**9; // uint256 public _swapTokensAtAmount = 10000 * 10**9; // event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);// uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true; bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true; bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true; bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true; bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true; bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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 from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { //Trade start check if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } //Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, 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 ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchBlock = block.number; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } 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 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set maximum transaction function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
Buy FeeSell FeeOriginal Fee
contract MetaMind is Context, IERC20, Ownable { using SafeMath for uint256; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true; bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true; bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true; bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true; bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true; bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { 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 tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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 from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, 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 ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchBlock = block.number; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } 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 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
14,886,875
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 6565, 49, 728, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 7010, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 7010, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 2130, 12648, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 565, 2254, 5034, 1071, 8037, 1768, 31, 203, 7010, 7010, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 273, 389, 12311, 14667, 1398, 55, 1165, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 273, 389, 8066, 14667, 1398, 55, 1165, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 11515, 12311, 14667, 273, 389, 12311, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 1484, 522, 83, 641, 651, 14667, 273, 389, 8066, 14667, 31, 203, 7010, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 2512, 87, 31, 203, 565, 2874, 12, 2867, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./Pausable.sol"; /// @title Advertisement Manager Contract /// @author Mariona (seaona) /// @notice Do not use this contract on production contract AdsManager is Pausable { /// @dev Using SafeMath to protect from overflow and underflow using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ /// @dev Advertisement variables mapping (uint => Ad) ads; uint256 public adsCounter; /// @dev Total Advertisement Area available is an abstract representation of the surface of the website available for Ads uint256 public totalAdAreaAvailable = 100; /// @dev Total Advertisement Taken is an abstract representation of the surface of the website dedicated to certains ad uint256 public totalAdAreaTaken = 0; /// @dev Total max area for advertisement cannot be updated as website space for advertisements is limited uint256 constant public totalAdMaxArea = 500; /// @dev Ads can be ForSale or Sold enum State { ForSale, Sold } /// @dev Big = 50 units of area, Medium = 25 units of area, Small = 10 units of area enum Size { Big, Medium, Small } /// @dev This is an Advertisement item struct Ad { State state; Size size; bytes32 brand; address payable owner; uint256 price; } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /// @dev Event that is emitted when Advertisement Area is put for sale event AdAreaForSale(uint32 _adId); /// @dev Event that is emitted when Advertisement Area is bought event AdAreaBought(uint32 _adId); /// @dev Event that is emitted when the owner of the website adds extra a Small Advertisement Area for sale event SmallAdAreaAdded(Size _size); /// @dev Event that is emitted when the owner of the website adds extra a Medium Advertisement Area for sale event MediumAdAreaAdded(Size _size); /// @dev Event that is emitted when the owner of the website adds extra a Big Advertisement Area for sale event BigAdAreaAdded(Size _size); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ /// @dev Modifier that throws if called by any account other than the Advertisement Owner modifier onlyAdOwner(uint32 _adId) { require(msg.sender == ads[_adId].owner, "You are not the owner of this Ad Area"); _; } /// @dev Modifier that throws if not paid enough for the Ad modifier paidEnough(uint _adId) { require(msg.value >= ads[_adId].price, "You haven't paid enough for buying this Ad space"); _; } /// @dev Modifier that throws if there is not enough Advertisement area available modifier enoughAdArea(uint _area) { require(_area <= totalAdMaxArea, "There is not enough Advertisement area available"); _; } /********************************************************************************************/ /* UTIL FUNCTIONS */ /********************************************************************************************/ /// @dev Get the total number of Ads Areas /// @return Total Ads Areas function getAdsCounter() public view returns (uint256) { return adsCounter; } /// @dev Get the total Advertisement area for that website /// @return Total Advertisement Area function getTotalAdMaxArea() public view returns(uint256) { return totalAdMaxArea; } /// @dev Get the total Advertisement area taken for that website /// @return Total Advertisement Area taken by Brands function getTotalAdAreaTaken() public view returns(uint256) { return totalAdAreaAvailable; } /// @dev Get the total Advertisement area available for ads that website /// @return Total Advertisement Area available for Brands function getTotalAdAreaAvailable() public view returns(uint256) { return totalAdAreaTaken; } /// @dev Get Ad Owner /// @return Address of Ad Owner function getAdOwner(uint32 _id) public view returns(address) { return ads[_id].owner; } /// @dev Get Ad status /// @return enum status: ForSale or Sold function getAdStatus(uint32 _id) public view returns(State) { return ads[_id].state; } /// @dev Get Ad size /// @return enum size: Big, Medium, Small function getAdSize(uint32 _id) public view returns(Size) { return ads[_id].size; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /// @dev Website Owner Adds a Small Advertisement Area /// @return Total Advertisement Area available for Brands function addSmallAdvertisementSpace() public onlyOwner whenNotPaused returns (uint256) { require(totalAdAreaAvailable+totalAdAreaTaken+10 <= totalAdMaxArea, "Ads Area is already completed"); ads[adsCounter].state = State.ForSale; ads[adsCounter].size = Size.Small; ads[adsCounter].brand = "For Sale"; ads[adsCounter].owner = payable(msg.sender); ads[adsCounter].price = 100; adsCounter++; totalAdAreaTaken + 10; totalAdAreaAvailable = totalAdAreaAvailable + 10; emit SmallAdAreaAdded(Size.Small); return totalAdAreaAvailable; } /// @dev Website Owner Adds a Medium Advertisement Area /// @return Total Advertisement Area available for Brands function addMediumAdvertisementSpace() public onlyOwner whenNotPaused returns (uint256) { require(totalAdAreaAvailable+totalAdAreaTaken+25 <= totalAdMaxArea, "Ads Area is already completed"); ads[adsCounter].state = State.ForSale; ads[adsCounter].size = Size.Medium; ads[adsCounter].brand = "For Sale"; ads[adsCounter].owner = payable(msg.sender); ads[adsCounter].price = 250; adsCounter++; totalAdAreaTaken + 25; totalAdAreaAvailable = totalAdAreaAvailable + 25; emit MediumAdAreaAdded(Size.Medium); return totalAdAreaAvailable; } /// @dev Website Owner Adds a Big Advertisement Area /// @return Total Advertisement Area available for Brands function addBigAdvertisementSpace() public onlyOwner whenNotPaused returns (uint256) { require(totalAdAreaAvailable+totalAdAreaTaken+50 <= totalAdMaxArea, "Ads Area is already completed"); ads[adsCounter].state = State.ForSale; ads[adsCounter].size = Size.Big; ads[adsCounter].brand = "For Sale"; ads[adsCounter].owner = payable(msg.sender); ads[adsCounter].price = 500; adsCounter++; totalAdAreaTaken +50; totalAdAreaAvailable = totalAdAreaAvailable + 50; emit BigAdAreaAdded(Size.Big); return totalAdAreaAvailable; } /// @dev Revoke Ad from Brand function revokeAdFromBrand(uint32 _adId) public onlyOwner whenNotPaused returns (bool) { require(ads[_adId].state == State.Sold, "This Advertisement space is already available"); uint256 adSize; if(ads[_adId].size==Size.Big) { adSize = 50; } if(ads[_adId].size==Size.Medium) { adSize = 25; } if(ads[_adId].size==Size.Small) { adSize = 10; } ads[_adId].state = State.ForSale; ads[_adId].owner = payable(msg.sender); ads[_adId].brand = "For Sale"; totalAdAreaAvailable = totalAdAreaAvailable + adSize; return true; } /// @dev Brand buys Advertisement Area function buyAdArea(uint32 _adId) public payable paidEnough(_adId) whenNotPaused { require(ads[_adId].state == State.ForSale, "Ad Area is not for Sale"); uint256 amountToRefund = msg.value - ads[_adId].price; ads[_adId].owner = payable(msg.sender); ads[_adId].owner.transfer(amountToRefund); ads[_adId].state = State.Sold; emit AdAreaBought(_adId); } /// @dev Give back Ad ownership to website owner function handOverOwnership(uint32 _adId) public whenNotPaused returns (bool) { require(ads[_adId].owner == msg.sender, "You are not the owner of this Ad"); ads[_adId].state = State.ForSale; ads[_adId].owner = payable(0x0297196d753045df822C67d23F9aB10c7128b102); return true; } }
@dev Website Owner Adds a Medium Advertisement Area @return Total Advertisement Area available for Brands
function addMediumAdvertisementSpace() public onlyOwner whenNotPaused returns (uint256) { require(totalAdAreaAvailable+totalAdAreaTaken+25 <= totalAdMaxArea, "Ads Area is already completed"); ads[adsCounter].state = State.ForSale; ads[adsCounter].size = Size.Medium; ads[adsCounter].brand = "For Sale"; ads[adsCounter].owner = payable(msg.sender); ads[adsCounter].price = 250; adsCounter++; totalAdAreaTaken + 25; totalAdAreaAvailable = totalAdAreaAvailable + 25; emit MediumAdAreaAdded(Size.Medium); return totalAdAreaAvailable; }
12,591,323
[ 1, 19186, 16837, 15605, 279, 20158, 5077, 4052, 1097, 291, 820, 16668, 327, 10710, 4052, 1097, 291, 820, 16668, 2319, 364, 605, 86, 5708, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 25599, 1871, 1097, 291, 820, 3819, 1435, 1071, 1338, 5541, 1347, 1248, 28590, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 4963, 1871, 5484, 5268, 15, 4963, 1871, 5484, 27486, 15, 2947, 1648, 2078, 1871, 2747, 5484, 16, 315, 1871, 87, 16668, 353, 1818, 5951, 8863, 203, 203, 3639, 12767, 63, 17318, 4789, 8009, 2019, 273, 3287, 18, 1290, 30746, 31, 203, 3639, 12767, 63, 17318, 4789, 8009, 1467, 273, 6321, 18, 25599, 31, 203, 3639, 12767, 63, 17318, 4789, 8009, 20523, 273, 315, 1290, 348, 5349, 14432, 203, 3639, 12767, 63, 17318, 4789, 8009, 8443, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 3639, 12767, 63, 17318, 4789, 8009, 8694, 273, 16927, 31, 203, 203, 3639, 12767, 4789, 9904, 31, 203, 203, 3639, 2078, 1871, 5484, 27486, 397, 6969, 31, 203, 3639, 2078, 1871, 5484, 5268, 273, 2078, 1871, 5484, 5268, 397, 6969, 31, 203, 203, 3639, 3626, 20158, 5077, 1871, 5484, 8602, 12, 1225, 18, 25599, 1769, 203, 3639, 327, 2078, 1871, 5484, 5268, 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 ]
./partial_match/56/0x136B588534566500e2bc07cc53c7a390c3F1B22b/sources/StrategyAyreCryptoCakeBnbCake.sol
require(msg.sender == strategist || msg.sender == governance, "!authorized");
function harvest() public returns (uint harvesterRewarded) { require(msg.sender == tx.origin, "not eoa"); _stakeWant(); uint _cake = IERC20(cake).balanceOf(address(this)); uint256 _harvesterReward; if (_cake > 0) { uint256 _fee = _cake.mul(performanceFee).div(FEE_DENOMINATOR); uint256 _reward = _cake.mul(strategistReward).div(FEE_DENOMINATOR); _harvesterReward = _cake.mul(harvesterReward).div(FEE_DENOMINATOR); IERC20(cake).safeTransfer(IController(controller).rewards(), _fee); IERC20(cake).safeTransfer(strategist, _reward); IERC20(cake).safeTransfer(msg.sender, _harvesterReward); } _convertCakeToWant(); _stakeWant(); return _harvesterReward; }
11,196,454
[ 1, 6528, 12, 3576, 18, 15330, 422, 609, 1287, 376, 747, 1234, 18, 15330, 422, 314, 1643, 82, 1359, 16, 17528, 8434, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 1435, 1071, 1135, 261, 11890, 17895, 3324, 387, 17631, 17212, 13, 288, 203, 1377, 2583, 12, 3576, 18, 15330, 422, 2229, 18, 10012, 16, 315, 902, 425, 11867, 8863, 203, 203, 1377, 389, 334, 911, 59, 970, 5621, 203, 203, 1377, 2254, 389, 23780, 273, 467, 654, 39, 3462, 12, 23780, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 7010, 1377, 2254, 5034, 389, 30250, 3324, 387, 17631, 1060, 31, 203, 1377, 309, 261, 67, 23780, 405, 374, 13, 288, 203, 3639, 2254, 5034, 389, 21386, 273, 389, 23780, 18, 16411, 12, 16092, 1359, 14667, 2934, 2892, 12, 8090, 41, 67, 13296, 1872, 706, 3575, 1769, 203, 3639, 2254, 5034, 389, 266, 2913, 273, 389, 23780, 18, 16411, 12, 701, 1287, 376, 17631, 1060, 2934, 2892, 12, 8090, 41, 67, 13296, 1872, 706, 3575, 1769, 203, 3639, 389, 30250, 3324, 387, 17631, 1060, 273, 389, 23780, 18, 16411, 12, 30250, 3324, 387, 17631, 1060, 2934, 2892, 12, 8090, 41, 67, 13296, 1872, 706, 3575, 1769, 203, 3639, 467, 654, 39, 3462, 12, 23780, 2934, 4626, 5912, 12, 45, 2933, 12, 5723, 2934, 266, 6397, 9334, 389, 21386, 1769, 203, 3639, 467, 654, 39, 3462, 12, 23780, 2934, 4626, 5912, 12, 701, 1287, 376, 16, 389, 266, 2913, 1769, 203, 3639, 467, 654, 39, 3462, 12, 23780, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 389, 30250, 3324, 387, 17631, 1060, 1769, 203, 1377, 289, 203, 203, 1377, 389, 6283, 31089, 774, 59, 970, 5621, 203, 1377, 389, 334, 911, 59, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; contract CPD { /// @notice EIP-20 token name for this token string public constant name = "Coinspaid"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CPD"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 800_000_000e18; // 800 million CPD /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @dev 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 checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 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 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 A record of states for signing / validating signatures mapping (address => uint256) 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, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new CPD token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @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 view returns (uint256) { 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, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "CPD::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); 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, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "CPD::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), "CPD::permit: invalid signature"); require(signatory == owner, "CPD::permit: unauthorized"); require(now <= deadline, "CPD::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 returns (uint256) { 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, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "CPD::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, uint256 rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "CPD::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "CPD::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, uint256 nonce, uint256 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), "CPD::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CPD::delegateBySig: invalid nonce"); require(now <= expiry, "CPD::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, "CPD::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]; 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), "CPD::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "CPD::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "CPD::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "CPD::_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, "CPD::_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, "CPD::_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, "CPD::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 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 pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
* @notice Approve `spender` to transfer up to `amount` from `src` @dev This will overwrite the approval amount for `spender` @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, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); amount = safe96(rawAmount, "CPD::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
11,756,597
[ 1, 12053, 537, 1375, 87, 1302, 264, 68, 358, 7412, 731, 358, 1375, 8949, 68, 628, 1375, 4816, 68, 225, 1220, 903, 6156, 326, 23556, 3844, 364, 1375, 87, 1302, 264, 68, 225, 17571, 264, 1021, 1758, 434, 326, 2236, 1492, 2026, 7412, 2430, 225, 1831, 6275, 1021, 1300, 434, 2430, 716, 854, 20412, 261, 22, 66, 5034, 17, 21, 4696, 14853, 13, 327, 17403, 578, 486, 326, 23556, 15784, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 1831, 6275, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 10525, 3844, 31, 203, 3639, 309, 261, 1899, 6275, 422, 2254, 5034, 19236, 21, 3719, 288, 203, 5411, 3844, 273, 2254, 10525, 19236, 21, 1769, 203, 5411, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 4258, 40, 2866, 12908, 537, 30, 3844, 14399, 19332, 4125, 8863, 203, 3639, 289, 203, 203, 3639, 1699, 6872, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 3844, 31, 203, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Upgraded Date: 01-28-2022 // Commits: https://github.com/Sperax/USDs/commit/177c1f24c9de18940ec0b5ddce996f87b2343b8d#diff-b094db7ce2f99cbcbde7ec178a6754bac666e2192f076807acbd70d49ddd0559 // https://github.com/Sperax/USDs/commit/7d5d63260f7b0088f4aac60c690bc4a1b9265f2f#diff-b094db7ce2f99cbcbde7ec178a6754bac666e2192f076807acbd70d49ddd0559 // https://github.com/Sperax/USDs/commit/6ebcb7bb4ce895474953a98a2e518db31ed649b5#diff-b094db7ce2f99cbcbde7ec178a6754bac666e2192f076807acbd70d49ddd0559 // Changes: 1. now the contract collects yield in the token with higher return, // instead of in the original invested token // 2. optimized token flow of withdrawal // Implementation Contract Address: // 1. USDC strategy: 0x5D2A5d67fD5C970A4A4Ab60bA6cF9b438f869fb9 // 2. USDT strategy: 0xa2255E689D1E4cC82a7cDC1F01CAe603C93Fd92D // SPDX-License-Identifier: MIT /** * @title Curve 2Pool Strategy * @notice Investment strategy for investing stablecoins via Curve 2Pool * @author Sperax Inc */ pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import './interfaces/IOracleV2.sol'; import { ICurve2PoolV2 } from "./interfaces/ICurve2PoolV2.sol"; import { ICurveGauge } from "../interfaces/ICurveGauge.sol"; import { InitializableAbstractStrategyV2 } from "./interfaces/InitializableAbstractStrategyV2.sol"; import { StableMath } from "../libraries/StableMath.sol"; contract TwoPoolStrategyV2 is InitializableAbstractStrategyV2 { using StableMath for uint256; using SafeERC20 for IERC20; event SlippageChanged(uint256 newSlippage); event ThresholdChanged(uint256 newThreshold); // minimum LP needed when calculating LP to asset conversion uint256 public lpAssetThreshold = 3000; uint256 public lpAssetSlippage = 9800000; uint256 internal supportedAssetIndex; ICurveGauge public curveGauge; ICurve2PoolV2 public curvePool; IOracleV2 public oracle; /** * Initializer for setting up strategy internal state. This overrides the * InitializableAbstractStrategy initializer as Curve strategies don't fit * well within that abstraction. * @param _platformAddress Address of the Curve 2Pool * @param _vaultAddress Address of the vault * @param _rewardTokenAddress Address of CRV * @param _assets Addresses of supported assets. MUST be passed in the same * order as returned by coins on the pool contract, i.e. * DAI, USDC, USDT * @param _pTokens Platform Token corresponding addresses * @param _crvGaugeAddress Address of the Curve DAO gauge for this pool */ function initialize( address _platformAddress, // 2Pool address address _vaultAddress, address _rewardTokenAddress, // CRV address[] calldata _assets, address[] calldata _pTokens, address _crvGaugeAddress, uint256 _supportedAssetIndex, address _oracleAddr ) external initializer { require(_assets.length == 2, "Must have exactly two assets"); require(_supportedAssetIndex < 2, "_supportedAssetIndex exceeds 2"); // Should be set prior to abstract initialize call otherwise // abstractSetPToken calls will fail curveGauge = ICurveGauge(_crvGaugeAddress); supportedAssetIndex = _supportedAssetIndex; oracle = IOracleV2(_oracleAddr); InitializableAbstractStrategyV2._initialize( _platformAddress, _vaultAddress, _rewardTokenAddress, _assets, _pTokens ); curvePool = ICurve2PoolV2(platformAddress); } /** * @dev change to a new lpAssetSlippage * @dev lpAssetSlippage set to 9900000 means the slippage is 1%; overall precision is 10000000; it is the slippage on the conversion between LP token and underlying collateral/asset * @param _lpAssetSlippage new slippage setting */ function changeSlippage(uint256 _lpAssetSlippage) external onlyOwner { require(_lpAssetSlippage <= 10000000, 'Slippage exceeds 100%'); lpAssetSlippage = _lpAssetSlippage; emit SlippageChanged(lpAssetSlippage); } /** * @dev change to a new lpAssetThreshold * @dev lpAssetThreshold should be set to the minimum number of totalPTokens such that curvePool.calc_withdraw_one_coin does not revert * @param _lpAssetThreshold new lpAssetThreshold */ function changeThreshold(uint256 _lpAssetThreshold) external onlyOwner { lpAssetThreshold = _lpAssetThreshold; emit ThresholdChanged(lpAssetThreshold); } /** * @dev Check if an asset/collateral is supported. * @param _asset Address of the asset * @return bool Whether asset is supported */ function supportsCollateral( address _asset ) public view override returns (bool) { if (assetToPToken[_asset] != address(0) && _getPoolCoinIndex(_asset) == supportedAssetIndex) { return true; } else { return false; } } /** * @dev Deposit asset into the Curve 2Pool * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function deposit(address _asset, uint256 _amount) external override onlyVault nonReentrant { require(supportsCollateral(_asset), "Unsupported collateral"); require(_amount > 0, "Must deposit something"); // 2Pool requires passing deposit amounts for both 2 assets, set to 0 for // all uint256[2] memory _amounts; uint256 poolCoinIndex = _getPoolCoinIndex(_asset); // Set the amount on the asset we want to deposit _amounts[poolCoinIndex] = _amount; uint256 expectedPtokenAmt = _getExpectedPtokenAmt(_amount, _asset); uint256 minMintAmount = expectedPtokenAmt .mul(lpAssetSlippage) .div(10000000); // Do the deposit to 2Pool // triger to deposit LP tokens curvePool.add_liquidity(_amounts, minMintAmount); allocatedAmt[_asset] = allocatedAmt[_asset].add(_amount); // Deposit into Gauge IERC20 pToken = IERC20(assetToPToken[_asset]); curveGauge.deposit( pToken.balanceOf(address(this)) ); emit Deposit(_asset, address(assetToPToken[_asset]), _amount); } function withdraw( address _recipient, address _asset, uint256 _amount ) external override onlyVault nonReentrant { _withdraw(_recipient, _asset, _amount); } /** * @dev Withdraw asset from Curve 2Pool * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function withdrawToVault( address _asset, uint256 _amount ) external override onlyOwner nonReentrant { _withdraw(vaultAddress, _asset, _amount); } /** * @dev Collect interest earned from 2Pool * @param _recipient Address to receive withdrawn asset * @param _asset Asset type deposited into this strategy contract */ function collectInterest( address _recipient, address _asset ) external override onlyVault nonReentrant returns ( address interestAsset, uint256 interestAmt ) { require(_recipient != address(0), "Invalid recipient"); require(supportsCollateral(_asset), "Unsupported collateral"); (uint256 contractPTokens, , uint256 totalPTokens) = _getTotalPTokens(); uint256 assetInterest = checkInterestEarned(_asset); require(assetInterest > 0, "No interest earned"); (uint256 maxReturn, address returnAsset) = _checkMaxReturn(); interestAsset = returnAsset; if (returnAsset != _asset) { assetInterest = _convertBewteen( supportedAssetIndex, _getPoolCoinIndex(returnAsset), assetInterest ); } uint256 maxBurnedPTokens = totalPTokens .mul(assetInterest) .div(maxReturn); // Not enough in this contract or in the Gauge, can't proceed require(totalPTokens >= maxBurnedPTokens, "Insufficient 2CRV balance"); // We have enough LP tokens, make sure they are all on this contract if (contractPTokens < maxBurnedPTokens) { // Not enough of pool token exists on this contract, some must be // staked in Gauge, unstake difference curveGauge.withdraw( maxBurnedPTokens.sub(contractPTokens) ); } (contractPTokens, , ) = _getTotalPTokens(); maxBurnedPTokens = maxBurnedPTokens < contractPTokens ? maxBurnedPTokens : contractPTokens; uint256 minRedeemAmount = _getExpectedAssetAmt(maxBurnedPTokens, returnAsset) .mul(lpAssetSlippage) .div(10000000); interestAmt = curvePool.remove_liquidity_one_coin( maxBurnedPTokens, int128(_getPoolCoinIndex(returnAsset)), minRedeemAmount, _recipient ); emit InterestCollected( returnAsset, address(assetToPToken[_asset]), interestAmt ); } /** * @dev Collect accumulated CRV and send to Vault. */ function collectRewardToken() external override onlyVault nonReentrant { IERC20 crvToken = IERC20(rewardTokenAddress); uint256 balance_before = crvToken.balanceOf(vaultAddress); curveGauge.claim_rewards(address(this), vaultAddress); uint256 balance_after = crvToken.balanceOf(vaultAddress); emit RewardTokenCollected(vaultAddress, balance_after.sub(balance_before)); } /** * @dev Approve the spending of all assets by their corresponding pool tokens, * if for some reason is it necessary. */ function safeApproveAllTokens() override onlyOwner external { // This strategy is a special case since it only supports one asset _abstractSetPToken( assetsMapped[supportedAssetIndex], assetToPToken[assetsMapped[supportedAssetIndex]] ); } /** * @dev Get the total asset value held in the platform * @param _asset Address of the asset * @return balance Total amount of the asset in the platform */ function checkBalance(address _asset) public override view returns (uint256 balance) { require(supportsCollateral(_asset), "Unsupported collateral"); (uint256 maxReturn, address returnAsset) = _checkMaxReturn(); if (_asset != returnAsset) { balance = _convertBewteen( _getPoolCoinIndex(returnAsset), supportedAssetIndex, maxReturn ); } else { balance = maxReturn; } } /** * @dev Get the amount of asset/collateral earned as interest * @param _asset Address of the asset * @return interestEarned The amount of asset/collateral earned as interest */ function checkInterestEarned(address _asset) public view override returns (uint256) { require(supportsCollateral(_asset), "Unsupported collateral"); uint256 balance = checkBalance(_asset); if (balance > allocatedAmt[_asset]) { return balance.sub(allocatedAmt[_asset]); } else { return 0; } } /** * @dev Withdraw asset from Curve 2Pool * @param _recipient Address to receive withdrawn asset * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function _withdraw( address _recipient, address _asset, uint256 _amount ) internal { require(_recipient != address(0), "Invalid recipient"); require(supportsCollateral(_asset), "Unsupported collateral"); require(_amount > 0, "Invalid amount"); (uint256 contractPTokens, , uint256 totalPTokens) = _getTotalPTokens(); // Calculate how many platform tokens we need to withdraw the asset // amount in the worst case (i.e withdrawing all LP tokens) require(totalPTokens > 0, "Insufficient 2CRV balance"); uint256 maxAmount = 0; if (totalPTokens > lpAssetThreshold) { maxAmount = curvePool.calc_withdraw_one_coin( totalPTokens, int128(_getPoolCoinIndex(_asset)) ); } uint256 maxBurnedPTokens = totalPTokens.mul(_amount).div(maxAmount); // Not enough in this contract or in the Gauge, can't proceed require(totalPTokens >= maxBurnedPTokens, "Insufficient 2CRV balance"); // We have enough LP tokens, make sure they are all on this contract if (contractPTokens < maxBurnedPTokens) { // Not enough of pool token exists on this contract, some must be // staked in Gauge, unstake difference curveGauge.withdraw( maxBurnedPTokens.sub(contractPTokens) ); } (contractPTokens, , ) = _getTotalPTokens(); maxBurnedPTokens = maxBurnedPTokens < contractPTokens ? maxBurnedPTokens : contractPTokens; uint256 expectedAssetAmt = _getExpectedAssetAmt(maxBurnedPTokens, _asset); uint256 minRedeemAmount = expectedAssetAmt .mul(lpAssetSlippage) .div(10000000); uint256 _amount_received = curvePool.remove_liquidity_one_coin( maxBurnedPTokens, int128(_getPoolCoinIndex(_asset)), minRedeemAmount, _recipient ); if (_amount_received >= allocatedAmt[_asset]) { allocatedAmt[_asset] = 0; } else { allocatedAmt[_asset] = allocatedAmt[_asset].sub(_amount_received); } emit Withdrawal(_asset, address(assetToPToken[_asset]), _amount_received); } /** * @dev Call the necessary approvals for the Curve pool and gauge * @param _asset Address of the asset * @param _pToken Address of the corresponding platform token (i.e. 2CRV) */ function _abstractSetPToken(address _asset, address _pToken) override internal { IERC20 asset = IERC20(_asset); IERC20 pToken = IERC20(_pToken); // 2Pool for asset (required for adding liquidity) asset.safeApprove(platformAddress, 0); asset.safeApprove(platformAddress, uint256(-1)); // 2Pool for LP token (required for removing liquidity) pToken.safeApprove(platformAddress, 0); pToken.safeApprove(platformAddress, uint256(-1)); // Gauge for LP token pToken.safeApprove(address(curveGauge), 0); pToken.safeApprove(address(curveGauge), uint256(-1)); } /** * @dev Calculate the total platform token balance (i.e. 2CRV) that exist in * this contract or is staked in the Gauge (or in other words, the total * amount platform tokens we own). */ function _getTotalPTokens() internal view returns ( uint256 contractPTokens, uint256 gaugePTokens, uint256 totalPTokens ) { contractPTokens = IERC20(assetToPToken[assetsMapped[0]]).balanceOf( address(this) ); gaugePTokens = curveGauge.balanceOf(address(this)); totalPTokens = contractPTokens.add(gaugePTokens); } /** * @dev Get the index of the coin in 2Pool */ function _getPoolCoinIndex(address _asset) internal view returns (uint256) { for (uint256 i = 0; i < 2; i++) { if (assetsMapped[i] == _asset) return i; } revert("Unsupported collateral"); } /** * @dev Get the expected amount of asset/collateral when redeeming LP tokens * @param lpTokenAmt Amount of LP token to redeem * @param _asset Address of the asset * @return expectedAssetAmt the expected amount of asset/collateral token received */ function _getExpectedAssetAmt( uint256 lpTokenAmt, address _asset ) internal view returns (uint256 expectedAssetAmt) { uint256 assetPrice_prec = oracle.getCollateralPrice_prec(_asset); uint256 assetPrice = oracle.getCollateralPrice(_asset); expectedAssetAmt = lpTokenAmt .mul(curvePool.get_virtual_price()) .mul(assetPrice_prec) .div(assetPrice) .div(1e18) //get_virtual_price()'s precsion .scaleBy(int8(ERC20(_asset).decimals() - 18)); } /** * @dev Get the expected amount of lp when adding liquidity * @param assetAmt Amount of asset/collateral * @param _asset Address of the asset * @return expectedPtokenAmt the expected amount of lp token received */ function _getExpectedPtokenAmt( uint256 assetAmt, address _asset ) internal view returns (uint256 expectedPtokenAmt) { uint256 assetPrice_prec = oracle.getCollateralPrice_prec(_asset); uint256 assetPrice = oracle.getCollateralPrice(_asset); expectedPtokenAmt = assetAmt .scaleBy(int8(18 - ERC20(_asset).decimals())) .mul(assetPrice) .mul(1e18) .div(curvePool.get_virtual_price()) .div(assetPrice_prec); } /** * @notice Convert between USDC and USDT using Chainlink oracle * @dev The calculation here assume two tokens have the same decimals * @param index_from Index of the token to convert from * @param index_to Index of the token to convert to * @param amount_from amount of the token to convert from * @return amount_to amount of the token to convert to */ function _convertBewteen( uint256 index_from, uint256 index_to, uint256 amount_from ) internal view returns (uint256 amount_to) { require(index_from != index_to, 'Conversion between the same asset'); address token_from = assetsMapped[index_from]; address token_to = assetsMapped[index_to]; uint256 tokenPrice_from = oracle.getCollateralPrice(token_from); uint256 tokenPrice_to = oracle.getCollateralPrice(token_to); uint256 tokenPricePrecision_from = oracle .getCollateralPrice_prec(token_from); uint256 tokenPricePrecision_to = oracle .getCollateralPrice_prec(token_to); amount_to = amount_from .mul(tokenPrice_from) .mul(tokenPricePrecision_to) .div(tokenPrice_to) .div(tokenPricePrecision_from); } /** * @notice Get the total asset value held in the platform * @return maxReturn The amount of maximum returnAsset token redeemable * @return returnAsset The token that lp tokens are redeemed to */ function _checkMaxReturn() internal view returns (uint256 maxReturn, address returnAsset) { (, , uint256 totalPTokens) = _getTotalPTokens(); uint256 index_swappedToken = supportedAssetIndex == 1 ? 0 : 1; uint256 balanceNoSwap_originalToken = 0; uint256 balanceSwap_swappedToken = 0; uint256 balanceSwap_originalToken = 0; if (totalPTokens > lpAssetThreshold) { balanceNoSwap_originalToken = curvePool.calc_withdraw_one_coin( totalPTokens, int128(supportedAssetIndex) ); balanceSwap_swappedToken = curvePool.calc_withdraw_one_coin( totalPTokens, int128(index_swappedToken) ); balanceSwap_originalToken = _convertBewteen( supportedAssetIndex, index_swappedToken, balanceSwap_swappedToken ); } maxReturn = balanceNoSwap_originalToken > balanceSwap_originalToken ? balanceNoSwap_originalToken : balanceSwap_swappedToken; returnAsset = balanceNoSwap_originalToken > balanceNoSwap_originalToken ? assetsMapped[supportedAssetIndex] : assetsMapped[index_swappedToken]; } }
* @dev Withdraw asset from Curve 2Pool @param _recipient Address to receive withdrawn asset @param _asset Address of asset to withdraw @param _amount Amount of asset to withdraw/ Calculate how many platform tokens we need to withdraw the asset amount in the worst case (i.e withdrawing all LP tokens) We have enough LP tokens, make sure they are all on this contract Not enough of pool token exists on this contract, some must be staked in Gauge, unstake difference
function _withdraw( address _recipient, address _asset, uint256 _amount ) internal { require(_recipient != address(0), "Invalid recipient"); require(supportsCollateral(_asset), "Unsupported collateral"); require(_amount > 0, "Invalid amount"); (uint256 contractPTokens, , uint256 totalPTokens) = _getTotalPTokens(); require(totalPTokens > 0, "Insufficient 2CRV balance"); uint256 maxAmount = 0; if (totalPTokens > lpAssetThreshold) { maxAmount = curvePool.calc_withdraw_one_coin( totalPTokens, int128(_getPoolCoinIndex(_asset)) ); } uint256 maxBurnedPTokens = totalPTokens.mul(_amount).div(maxAmount); if (contractPTokens < maxBurnedPTokens) { curveGauge.withdraw( maxBurnedPTokens.sub(contractPTokens) ); } (contractPTokens, , ) = _getTotalPTokens(); maxBurnedPTokens = maxBurnedPTokens < contractPTokens ? maxBurnedPTokens : contractPTokens; uint256 expectedAssetAmt = _getExpectedAssetAmt(maxBurnedPTokens, _asset); uint256 minRedeemAmount = expectedAssetAmt .mul(lpAssetSlippage) .div(10000000); uint256 _amount_received = curvePool.remove_liquidity_one_coin( maxBurnedPTokens, int128(_getPoolCoinIndex(_asset)), minRedeemAmount, _recipient ); if (_amount_received >= allocatedAmt[_asset]) { allocatedAmt[_asset] = 0; allocatedAmt[_asset] = allocatedAmt[_asset].sub(_amount_received); } emit Withdrawal(_asset, address(assetToPToken[_asset]), _amount_received); }
2,572,226
[ 1, 1190, 9446, 3310, 628, 22901, 576, 2864, 225, 389, 20367, 5267, 358, 6798, 598, 9446, 82, 3310, 225, 389, 9406, 5267, 434, 3310, 358, 598, 9446, 225, 389, 8949, 16811, 434, 3310, 358, 598, 9446, 19, 9029, 3661, 4906, 4072, 2430, 732, 1608, 358, 598, 9446, 326, 3310, 3844, 316, 326, 22952, 648, 261, 77, 18, 73, 598, 9446, 310, 777, 511, 52, 2430, 13, 1660, 1240, 7304, 511, 52, 2430, 16, 1221, 3071, 2898, 854, 777, 603, 333, 6835, 2288, 7304, 434, 2845, 1147, 1704, 603, 333, 6835, 16, 2690, 1297, 506, 384, 9477, 316, 19766, 16, 640, 334, 911, 7114, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12, 203, 3639, 1758, 389, 20367, 16, 203, 3639, 1758, 389, 9406, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 2713, 288, 203, 3639, 2583, 24899, 20367, 480, 1758, 12, 20, 3631, 315, 1941, 8027, 8863, 203, 3639, 2583, 12, 28064, 13535, 2045, 287, 24899, 9406, 3631, 315, 8544, 4508, 2045, 287, 8863, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 1941, 3844, 8863, 203, 3639, 261, 11890, 5034, 6835, 1856, 3573, 16, 269, 2254, 5034, 2078, 1856, 3573, 13, 273, 389, 588, 5269, 1856, 3573, 5621, 203, 3639, 2583, 12, 4963, 1856, 3573, 405, 374, 16, 315, 5048, 11339, 576, 5093, 58, 11013, 8863, 203, 3639, 2254, 5034, 943, 6275, 273, 374, 31, 203, 3639, 309, 261, 4963, 1856, 3573, 405, 12423, 6672, 7614, 13, 288, 203, 5411, 943, 6275, 273, 8882, 2864, 18, 12448, 67, 1918, 9446, 67, 476, 67, 12645, 12, 203, 7734, 2078, 1856, 3573, 16, 203, 7734, 509, 10392, 24899, 588, 2864, 27055, 1016, 24899, 9406, 3719, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 2254, 5034, 943, 38, 321, 329, 1856, 3573, 273, 2078, 1856, 3573, 18, 16411, 24899, 8949, 2934, 2892, 12, 1896, 6275, 1769, 203, 3639, 309, 261, 16351, 1856, 3573, 411, 943, 38, 321, 329, 1856, 3573, 13, 288, 203, 5411, 8882, 18941, 18, 1918, 9446, 12, 203, 7734, 943, 38, 321, 329, 1856, 3573, 18, 1717, 12, 16351, 1856, 3573, 13, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 261, 16351, 1856, 3573, 16, 269, 262, 2 ]
./partial_match/1/0x1BFDe68f5694678FB4C45E9aD40eBEdB835b6346/sources/BST.sol
enable cooldown between trades
function changeCooldownSettings(bool newStatus, uint256 newInterval) external onlyOwner { cooldownEnabled = newStatus; cooldownTimerInterval = newInterval; }
15,520,415
[ 1, 7589, 27367, 2378, 3086, 1284, 5489, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2549, 39, 1371, 2378, 2628, 12, 6430, 394, 1482, 16, 2254, 5034, 394, 4006, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 27367, 2378, 1526, 273, 394, 1482, 31, 203, 3639, 27367, 2378, 6777, 4006, 273, 394, 4006, 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 ]
./full_match/1/0xE83B94ECA0e76D9cE0119Fe6D37a539623C097D4/sources/contracts/staking/StakingPools.sol
* @notice Fetches the amount staked by a specific user in a specific pool @dev This function returns the stakeAmount from the UserData struct in the userData mapping for the user in the specified pool @param user The address of the user @param poolId The ID of the pool @return The amount staked by the user in the pool/
function getStakingAmountByPoolID(address user, uint256 poolId) external view override returns (uint256) { return userData[poolId][user].stakeAmount; }
8,402,146
[ 1, 14288, 326, 3844, 384, 9477, 635, 279, 2923, 729, 316, 279, 2923, 2845, 225, 1220, 445, 1135, 326, 384, 911, 6275, 628, 326, 31109, 1958, 1377, 316, 326, 13530, 2874, 364, 326, 729, 316, 326, 1269, 2845, 225, 729, 1021, 1758, 434, 326, 729, 225, 2845, 548, 1021, 1599, 434, 326, 2845, 327, 1021, 3844, 384, 9477, 635, 326, 729, 316, 326, 2845, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 21491, 6159, 6275, 858, 2864, 734, 12, 2867, 729, 16, 2254, 5034, 2845, 548, 13, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 13530, 63, 6011, 548, 6362, 1355, 8009, 334, 911, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2019 Staked Securely, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works 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, TITLE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE. */ pragma solidity 0.4.25; /// @notice Implementation of the Eternal Storage Pattern to enable the RAY /// smart contracts system to be upgradable. /// /// Author: Devan Purhar /// Version: 1.0.0 contract Storage { /*************** STORAGE VARIABLE DECLARATIONS **************/ // TODO: remove 'wallet', this will eventually be a contract, not an EOA address public governanceWalletAddress; mapping(address => bool) internal storageWrappers; // verified addresses to mutate Storage mapping(address => bool) internal oracles; // verified off-chain addresses to call the Oracle contract mapping(bytes32 => address) internal verifier; // verified contract for portfolio impls. mapping(bytes32 => address) internal contracts; // verified contracts of the system mapping(bytes32 => bytes32) internal tokenKeys; mapping(bytes32 => CommonState) internal _commonStorage; mapping(bytes32 => PortfolioState) internal _portfolioStorage; mapping(address => CoinState) internal _coinStorage; /// @notice Common state across RAY's and Opportunities struct CommonState { uint withdrawnYield; uint realizedYield; uint totalShareSupply; uint principal; // only used by Opportunities, only one principal balance to track per Opportunity pool bool pausedMode; address principalAddress; mapping(bytes32 => uint[4]) tokenValues; // include these for flexibility in the future mapping(bytes32 => bool) _bool; mapping(bytes32 => int) _int; mapping(bytes32 => uint) _uint; mapping(bytes32 => string) _string; mapping(bytes32 => address) _address; mapping(bytes32 => bytes) _bytes; } /// @notice Variables only Portfolios require struct PortfolioState { mapping(bytes32 => bytes32) opportunityTokens; bytes32[] opportunities; mapping(bytes32 => bool) validOpportunities; uint availableCapital; } /// @notice State that needs to be filled out for a coin to be added to the /// system. /// /// TODO: Remove minAmount. We should go back to only enforcing the technical /// minimal amount on-chain and leave any harder restrictions to GUI-side. /// It's not in favor of an 'open' system to have minimum limits. struct CoinState { uint benchmarkRate; uint cumulativeRate; uint lastUpdatedRate; // in seconds uint acpContribution; uint minAmount; uint raised; bool isERC20; } /*************** MODIFIER DECLARATIONS **************/ /// @notice Checks the caller is a valid Storage Wrapper /// /// @dev Only Storage Wrappers can mutate Storage's storage modifier onlyStorageWrappers() { require( storageWrappers[msg.sender] == true, "#Storage onlyStorageWrappers Modifier: Only StorageWrappers can call this" ); _; } /////////////////////// FUNCTION DECLARATIONS BEGIN /////////////////////// /******************* PUBLIC FUNCTIONS *******************/ /// @notice Sets the Admin contract to our wallet originally until we deploy /// the Admin contract (next step in deployment). Also sets our wallet /// wallet address as a storage wrapper, later unsets it. /// /// @param _governanceWalletAddress - governance's wallet address /// @param _weth - Canonical WETH9 contract address /// @param _dai - DAI token contract address constructor( address _governanceWalletAddress, address _weth, address _dai ) public { governanceWalletAddress = _governanceWalletAddress; contracts[keccak256("WETHTokenContract")] = _weth; contracts[keccak256("DAITokenContract")] = _dai; contracts[keccak256("AdminContract")] = msg.sender; // need to deploy Admin and then forgo this storageWrappers[msg.sender] = true; // need to deploy and set Storage Wrappers then forgo this } /** ----------------- GLOBAL VIEW ACCESSORS ----------------- **/ /// @notice Gets the current governance address /// /// @return governance address function getGovernanceWallet() external view returns (address) { return governanceWalletAddress; } /// @notice Checks if the entered address is an approved Oracle /// /// @param target - address we're checking out /// /// @return true or false function getIsOracle(address target) external view returns (bool) { return oracles[target]; } /// @notice Gets a contract address by a bytes32 hash (keccak256) /// /// @param contractName - Ex. keccak256("PortfolioManagerContract"); /// /// @return The contract address function getContractAddress(bytes32 contractName) external view returns (address) { return contracts[contractName]; } /// @notice Maps portfolio's to the contract that they currently are used /// through. Supports multiple versions of the same contracts /// /// @param contractName - Ex. keccak256("PortfolioManagerContract"); /// /// @return The contract address function getVerifier(bytes32 contractName) external view returns (address) { return verifier[contractName]; } /// @notice Each token is mapped to a key that unlocks everything for it /// in storage. /// /// @param tokenId - token id of the RAY token /// /// @return The portfolio id/key associated function getTokenKey(bytes32 tokenId) external view returns (bytes32) { return tokenKeys[tokenId]; } /** ----------------- STATE SPECIFIC-TYPE VIEW ACCESSOR ----------------- **/ /// @notice Get the Opportunities this portfolio is allowed to be in /// /// @param portfolioId - the id of the portfolio /// /// @return Array of valid opportunity id's function getOpportunities(bytes32 portfolioId) external view returns (bytes32[]) { return _portfolioStorage[portfolioId].opportunities; } /// @notice Get's the coin type of the entered RAY /// /// @param portfolioId - the id of the portfolio /// /// @return The coin associated with the portfolio /// /// TODO: Refactor to getPrincipalToken since we commonly use that function getPrincipalAddress(bytes32 portfolioId) external view returns (address) { return _commonStorage[portfolioId].principalAddress; } /// @notice Check if the entered coin is an ERC20 /// /// @param principalAddress - the coin contract address we're checking /// /// @return true or false function getIsERC20(address principalAddress) external view returns (bool) { return _coinStorage[principalAddress].isERC20; } /// @notice Get the min. amount for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return min. amount in smallest units in-kind /// /// TODO: Remove this (and refactor the check used in PositionManager associated) function getMinAmount(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].minAmount; } /// @notice Get the normalizer factor for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return multiplier to use on the input values for this coin function getRaised(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].raised; } /// @notice Gets the current benchmark rate of associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return benchmark rate function getBenchmarkRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].benchmarkRate; } /// @notice Gets the cumulative rate of the portfolio entered /// /// @dev The cumulative rate tracks how the benchmark rate has /// progressed over time. Used in our fee model to find /// what benchmark rate is appropriate to a unique token /// based on when they joined and the changes the rate /// went through in that time period before they withdraw. /// /// @param principalAddress - the coin contract address we're checking /// /// @return the cumulative benchmark rate function getCumulativeRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].cumulativeRate; } /// @notice Gets the last time in seconds the cumulative rate was /// was updated for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return Last time in seconds the cumulative rate was updated function getLastUpdatedRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].lastUpdatedRate; } /// @notice Gets the ACP Contribution for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return the acp contribution function getACPContribution(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].acpContribution; } /// @notice Checks if the opportunity is allowed for the associated portfolio /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity /// /// @return true or false function isValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external view returns (bool) { return _portfolioStorage[portfolioId].validOpportunities[opportunityId]; } /// @notice Get the shares of the associated token /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the number of shares function getTokenShares(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][0]; } /// @notice Get the capital of the associated token /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the amount of capital function getTokenCapital(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][1]; } /// @notice Gets the allowance of the associated token /// /// @dev Each token has an allowance which reflects how much yield they're /// able to make without being charged a fee by us. /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the amount of allowance function getTokenAllowance(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][2]; } /// @notice Gets the value of the cumulative rate the token 'entered' at. /// /// @dev I say 'entered' because when a token adds capital or partially withdraws /// or anytime it changes it's token capital we reset this. /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the entry rate in seconds /// /// TODO: Based on the above @dev we should refactor this to a more appropriate /// name function getEntryRate(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][3]; } /// @notice Gets the Opportunity Token of a portfolio. /// /// @dev We assume a portfolio will only need one of a certain Opportunity /// Token. It shouldn't ever need multiple of the same Opportunity. /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity /// /// @return The Opportunity token id function getOpportunityToken(bytes32 portfolioId, bytes32 opportunityId) external view returns (bytes32) { return _portfolioStorage[portfolioId].opportunityTokens[opportunityId]; } /// @notice Get the principal supplied for the Opportunity /// /// @param opportunityId - the id of the opportunity /// /// @return the amount of principal supplied function getPrincipal(bytes32 opportunityId) external view returns (uint) { return _commonStorage[opportunityId].principal; } /// @notice Check if in paused mode for the associated portfolio /// /// @param portfolioId - the id of the portfolio /// /// @return true or false function getPausedMode(bytes32 portfolioId) external view returns (bool) { return _commonStorage[portfolioId].pausedMode; } /// @notice Gets the realized yield of the associated portfolio /// /// @dev Realized yield is the yield we've made, but withdrew /// back into the system and now use it as capital /// /// @param portfolioId - the id of the portfolio /// /// @return the yield realized function getRealizedYield(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].realizedYield; } /// @notice Gets the withdrawn yield of the associated portfolio /// /// @param portfolioId - the id of the portfolio /// /// @return the yield withdrawn function getWithdrawnYield(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].withdrawnYield; } /// @notice Gets the available capital of the portfolio associated /// /// @dev Available capital is the amount of funds available to a portfolio. /// This is instantiated by users depositing funds /// /// @param portfolioId - the id of the portfolio /// /// @return the available capital function getAvailableCapital(bytes32 portfolioId) external view returns (uint) { return _portfolioStorage[portfolioId].availableCapital; } /// @notice Gets the share supply of the portfolio associated /// /// @param portfolioId - the id of the portfolio /// /// @return the total shares function getShareSupply(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].totalShareSupply; } /** ----------------- GENERIC TYPE VIEW ACCESSOR ----------------- **/ function getBoolean(bytes32 ray, bytes32 key) external view returns (bool) { return _commonStorage[ray]._bool[key]; } function getInt(bytes32 ray, bytes32 key) external view returns (int) { return _commonStorage[ray]._int[key]; } function getUint(bytes32 ray, bytes32 key) external view returns (uint) { return _commonStorage[ray]._uint[key]; } function getAddress(bytes32 ray, bytes32 key) external view returns (address) { return _commonStorage[ray]._address[key]; } function getString(bytes32 ray, bytes32 key) external view returns (string) { return _commonStorage[ray]._string[key]; } function getBytes(bytes32 ray, bytes32 key) external view returns (bytes) { return _commonStorage[ray]._bytes[key]; } /** ----------------- ONLY STORAGE WRAPPERS GLOBAL MUTATORS ----------------- **/ /// @notice This sets the Governance Wallet - important since this wallet controls /// the Admin contract that controls 'Governance' in the system. /// /// @param newGovernanceWallet - the new governance address function setGovernanceWallet(address newGovernanceWallet) external onlyStorageWrappers { governanceWalletAddress = newGovernanceWallet; } /// @dev Adds or remove an address to Oracle permissions status /// /// @param oracle - the address of the wallet targeted /// @param action - the action we wish to carry out, true to add, false to remove function setOracle(address oracle, bool action) external onlyStorageWrappers { oracles[oracle] = action; } /// @notice Adds or removes an address to StorageWrapper permissions status /// /// @param theStorageWrapper - the address to either add or remove /// @param action - the action we wish to carry out, true to add, false to remove function setStorageWrapperContract( address theStorageWrapper, bool action ) external onlyStorageWrappers { storageWrappers[theStorageWrapper] = action; } /// @notice Sets a portfolio or opportunity to a contract implementation /// /// @param typeId - the portfolio or opportunity id /// @param contractAddress - the contract address function setVerifier(bytes32 typeId, address contractAddress) external onlyStorageWrappers { verifier[typeId] = contractAddress; } /// @notice Sets the contract address mapped to a contracts name /// /// @param contractName - The name of the contract /// @param contractAddress - The address of the contract function setContractAddress( bytes32 contractName, address contractAddress ) external onlyStorageWrappers { contracts[contractName] = contractAddress; } /// @notice Sets a portfolio id to a token /// /// @param tokenId - The id of the token /// @param portfolioId - The id of the portfolio function setTokenKey(bytes32 tokenId, bytes32 portfolioId) external onlyStorageWrappers { tokenKeys[tokenId] = portfolioId; } /// @notice Sets status on ERC20 for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _isERC20 - true if is ERC20, false if not function setIsERC20(address principalAddress, bool _isERC20) external onlyStorageWrappers { _coinStorage[principalAddress].isERC20 = _isERC20; } /// @notice Sets the min. amount for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _minAmount - the min. amount in-kind smallest units function setMinAmount(address principalAddress, uint _minAmount) external onlyStorageWrappers { _coinStorage[principalAddress].minAmount = _minAmount; } /// @notice Sets the normalizing multiplier for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _raised - the multiplier function setRaised(address principalAddress, uint _raised) external onlyStorageWrappers { _coinStorage[principalAddress].raised = _raised; } /// @notice Sets the benchmark rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newBenchmarkRate - the new benchmark rate function setBenchmarkRate( address principalAddress, uint newBenchmarkRate ) external onlyStorageWrappers { _coinStorage[principalAddress].benchmarkRate = newBenchmarkRate; } /// @notice Sets the cumulative rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newCumulativeRate - the new cumulative rate function setCumulativeRate( address principalAddress, uint newCumulativeRate ) external onlyStorageWrappers { _coinStorage[principalAddress].cumulativeRate = newCumulativeRate; } /// @notice Sets the timestamp for last updating the rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newLastUpdatedRate - the new last updated rate function setLastUpdatedRate( address principalAddress, uint newLastUpdatedRate ) external onlyStorageWrappers { _coinStorage[principalAddress].lastUpdatedRate = newLastUpdatedRate; } /// @notice Sets the acp contribution for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newACPContribution - the new acp contribution function setACPContribution( address principalAddress, uint newACPContribution ) external onlyStorageWrappers { _coinStorage[principalAddress].acpContribution = newACPContribution; } /** ----------------- ONLY STORAGE WRAPPERS STATE SPECIFIC MUTATORS ----------------- **/ /// @notice Clears the data of the associated token (used upon a burn) /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token function deleteTokenValues(bytes32 portfolioId, bytes32 tokenId) external onlyStorageWrappers { delete _commonStorage[portfolioId].tokenValues[tokenId]; } /// @notice Add an Opportunity to a portfolio's available options. We also set /// the principal address used by the portfolio at the same time. /// /// @param portfolioId - The id of the portfolio we're configuring /// @param opportunityKey - The key of the opportunity we're adding to this portfolio /// @param _principalAddress - The coin's contract address for this portfolio // /// TODO: This is in-efficient, we set the principal address multiple times /// for the same portfolio. Fix this. /// /// TODO: Refactor principalToken -> principalAddress or opposite? function addOpportunity( bytes32 portfolioId, bytes32 opportunityKey, address _principalAddress ) external onlyStorageWrappers { _portfolioStorage[portfolioId].opportunities.push(opportunityKey); _commonStorage[portfolioId].principalAddress = _principalAddress; } /// @notice Set the principal address/coin of the associated portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param _principalAddress - The coin's contract address for this portfolio function setPrincipalAddress( bytes32 portfolioId, address _principalAddress ) external onlyStorageWrappers { _commonStorage[portfolioId].principalAddress = _principalAddress; } /// @notice Set an opportunity as valid in a mapping to a portfolio key /// /// @dev We set the valid opportunities in an array, but we also set them /// here for quicker access instead of having to iterate through the array. /// Sacrifice the extra gas cost (20,000) per opportunity we 'double set' /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity function setValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external onlyStorageWrappers { _portfolioStorage[portfolioId].validOpportunities[opportunityId] = true; } /// @notice Set the shares of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenShares - The number of shares function setTokenShares( bytes32 portfolioId, bytes32 tokenId, uint tokenShares ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][0] = tokenShares; } /// @notice Set the capital of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenCapital - The amount of capital function setTokenCapital( bytes32 portfolioId, bytes32 tokenId, uint tokenCapital ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][1] = tokenCapital; } /// @notice Set the allowance of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenAllowance - The amount of allowance function setTokenAllowance( bytes32 portfolioId, bytes32 tokenId, uint tokenAllowance ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][2] = tokenAllowance; } /// @notice Set the entry rate of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param entryRate - The entry rate (in seconds) function setEntryRate( bytes32 portfolioId, bytes32 tokenId, uint entryRate ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][3] = entryRate; } /// @notice Set the id of an Opportunity token for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param opportunityId - The id of the opportunity the token represents /// @param tokenId - The id of the Opportunity token function setOpportunityToken( bytes32 portfolioId, bytes32 opportunityId, bytes32 tokenId ) external onlyStorageWrappers { _portfolioStorage[portfolioId].opportunityTokens[opportunityId] = tokenId; } /// @notice Set the id of an Opportunity token for a portfolio /// /// @param opportunityId - The id of the opportunity the token represents /// @param principalAmount - The new amount of principal function setPrincipal( bytes32 opportunityId, uint principalAmount ) external onlyStorageWrappers { _commonStorage[opportunityId].principal = principalAmount; } /// @notice Set paused mode on for a portfolio /// /// @dev Enter keccak256("RAY") to pause all portfolios /// /// @param portfolioId - The id of the portfolio we're configuring function setPausedOn(bytes32 portfolioId) external onlyStorageWrappers { _commonStorage[portfolioId].pausedMode = true; } /// @notice Set paused mode off for a portfolio /// /// @dev Enter keccak256("RAY") to un-pause all portfolios /// /// @param portfolioId - The id of the portfolio we're configuring function setPausedOff(bytes32 portfolioId) external onlyStorageWrappers { _commonStorage[portfolioId].pausedMode = false; } /// @notice Set the realized yield for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newRealizedYield - The new realized yield function setRealizedYield(bytes32 portfolioId, uint newRealizedYield) external onlyStorageWrappers { _commonStorage[portfolioId].realizedYield = newRealizedYield; } /// @notice Set the withdrawn yield for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newWithdrawnYield - The new realized yield function setWithdrawnYield(bytes32 portfolioId, uint newWithdrawnYield) external onlyStorageWrappers { _commonStorage[portfolioId].withdrawnYield = newWithdrawnYield; } /// @notice Set the available capital for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newAvailableCapital - The new available capital function setAvailableCapital(bytes32 portfolioId, uint newAvailableCapital) external onlyStorageWrappers { _portfolioStorage[portfolioId].availableCapital = newAvailableCapital; } /// @notice Set the total share supply for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newShareSupply - The new share supply function setShareSupply(bytes32 portfolioId, uint newShareSupply) external onlyStorageWrappers { _commonStorage[portfolioId].totalShareSupply = newShareSupply; } /** ----------------- ONLY STORAGE WRAPPERS GENERIC MUTATORS ----------------- **/ /// @notice We have these to enable us to be flexible with our eternal storage /// in the future. Also, we could always deploy a new Storage contract /// and reference two Storage contracts in the system and so on. function setBoolean(bytes32 ray, bytes32 key, bool value) external onlyStorageWrappers { _commonStorage[ray]._bool[key] = value; } function setInt(bytes32 ray, bytes32 key, int value) external onlyStorageWrappers { _commonStorage[ray]._int[key] = value; } function setUint(bytes32 ray, bytes32 key, uint256 value) external onlyStorageWrappers { _commonStorage[ray]._uint[key] = value; } function setAddress(bytes32 ray, bytes32 key, address value) external onlyStorageWrappers { _commonStorage[ray]._address[key] = value; } function setString(bytes32 ray, bytes32 key, string value) external onlyStorageWrappers { _commonStorage[ray]._string[key] = value; } function setBytes(bytes32 ray, bytes32 key, bytes value) external onlyStorageWrappers { _commonStorage[ray]._bytes[key] = value; } }
@notice Variables only Portfolios require
struct PortfolioState { mapping(bytes32 => bytes32) opportunityTokens; bytes32[] opportunities; mapping(bytes32 => bool) validOpportunities; uint availableCapital; }
12,906,356
[ 1, 6158, 1338, 6008, 9002, 7441, 2583, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 6008, 10270, 1119, 288, 203, 203, 565, 2874, 12, 3890, 1578, 516, 1731, 1578, 13, 1061, 655, 13352, 5157, 31, 203, 565, 1731, 1578, 8526, 1061, 655, 318, 1961, 31, 203, 565, 2874, 12, 3890, 1578, 516, 1426, 13, 923, 3817, 655, 318, 1961, 31, 203, 565, 2254, 2319, 4664, 7053, 31, 203, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x26C190dDFDF7f7F7d59e06b80594A95206Ae1EA3/sources/ETH.sol
* @dev function to convert all dividend to collateral./ fetch dividends pay out the dividends virtually retrieve ref. bonus dispatch a buy order with the virtualized "withdrawn dividends" fire event
function reinvest(address contractAddress) public nonReentrant { address _customerAddress = msg.sender; balanceDetails[_customerAddress][contractAddress].payOut = SignedSafeMath.add(balanceDetails[_customerAddress][contractAddress].payOut, (int256) (SafeMath.mul(_dividends, magnitude))); _dividends = SafeMath.add(_dividends, balanceDetails[_customerAddress][contractAddress].referralBalance); balanceDetails[_customerAddress][contractAddress].referralBalance = 0; uint256 _collate = purchaseCollate(contractAddress, _dividends, address(0)); emit onReinvest(_customerAddress, contractAddress, _dividends, _collate); }
5,158,664
[ 1, 915, 358, 1765, 777, 31945, 358, 4508, 2045, 287, 18, 19, 2158, 3739, 350, 5839, 8843, 596, 326, 3739, 350, 5839, 331, 2714, 3452, 4614, 1278, 18, 324, 22889, 3435, 279, 30143, 1353, 598, 326, 5024, 1235, 315, 1918, 9446, 82, 3739, 350, 5839, 6, 4452, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 283, 5768, 395, 12, 2867, 6835, 1887, 13, 1071, 1661, 426, 8230, 970, 203, 565, 288, 203, 540, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 11013, 3790, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 10239, 1182, 273, 225, 16724, 9890, 10477, 18, 1289, 12, 12296, 3790, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 10239, 1182, 16, 261, 474, 5034, 13, 261, 9890, 10477, 18, 16411, 24899, 2892, 350, 5839, 16, 13463, 3719, 1769, 203, 540, 203, 3639, 389, 2892, 350, 5839, 273, 14060, 10477, 18, 1289, 24899, 2892, 350, 5839, 16, 11013, 3790, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 1734, 29084, 13937, 1769, 203, 540, 203, 3639, 11013, 3790, 63, 67, 10061, 1887, 6362, 16351, 1887, 8009, 1734, 29084, 13937, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 389, 12910, 340, 273, 23701, 13535, 340, 12, 16351, 1887, 16, 389, 2892, 350, 5839, 16, 1758, 12, 20, 10019, 203, 540, 203, 3639, 3626, 603, 426, 5768, 395, 24899, 10061, 1887, 16, 6835, 1887, 16, 389, 2892, 350, 5839, 16, 389, 12910, 340, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; contract IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns(bool); } contract IMerkleVerifier { uint256 constant internal MAX_N_MERKLE_VERIFIER_QUERIES = 128; function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash); } contract IQueryableFactRegistry is IFactRegistry { /* Returns true if at least one fact has been registered. */ function hasRegisteredFact() external view returns(bool); } contract IStarkVerifier { function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput ) internal; } contract MemoryMap { /* We store the state of the verifer in a contiguous chunk of memory. The offsets of the different fields are listed below. E.g. The offset of the i'th hash is [mm_hashes + i]. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; uint256 constant internal MAX_N_QUERIES = 48; uint256 constant internal FRI_QUEUE_SIZE = MAX_N_QUERIES; uint256 constant internal MAX_SUPPORTED_MAX_FRI_STEP = 4; uint256 constant internal MM_EVAL_DOMAIN_SIZE = 0x0; uint256 constant internal MM_BLOW_UP_FACTOR = 0x1; uint256 constant internal MM_LOG_EVAL_DOMAIN_SIZE = 0x2; uint256 constant internal MM_PROOF_OF_WORK_BITS = 0x3; uint256 constant internal MM_EVAL_DOMAIN_GENERATOR = 0x4; uint256 constant internal MM_PUBLIC_INPUT_PTR = 0x5; uint256 constant internal MM_TRACE_COMMITMENT = 0x6; uint256 constant internal MM_OODS_COMMITMENT = 0x7; uint256 constant internal MM_N_UNIQUE_QUERIES = 0x8; uint256 constant internal MM_CHANNEL = 0x9; // uint256[3] uint256 constant internal MM_MERKLE_QUEUE = 0xc; // uint256[96] uint256 constant internal MM_FRI_QUEUE = 0x6c; // uint256[144] uint256 constant internal MM_FRI_QUERIES_DELIMITER = 0xfc; uint256 constant internal MM_FRI_CTX = 0xfd; // uint256[40] uint256 constant internal MM_FRI_STEPS_PTR = 0x125; uint256 constant internal MM_FRI_EVAL_POINTS = 0x126; // uint256[10] uint256 constant internal MM_FRI_COMMITMENTS = 0x130; // uint256[10] uint256 constant internal MM_FRI_LAST_LAYER_DEG_BOUND = 0x13a; uint256 constant internal MM_FRI_LAST_LAYER_PTR = 0x13b; uint256 constant internal MM_CONSTRAINT_POLY_ARGS_START = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_A = 0x13c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_A = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_A = 0x13e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_A = 0x13f; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_A = 0x140; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_A = 0x141; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_A = 0x142; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_A = 0x143; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_A = 0x144; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_A = 0x145; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_B = 0x146; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_B = 0x147; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_B = 0x148; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_B = 0x149; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_B = 0x14a; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_B = 0x14b; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_B = 0x14c; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_B = 0x14d; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_B = 0x14e; uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_B = 0x14f; uint256 constant internal MM_MAT00 = 0x150; uint256 constant internal MM_MAT01 = 0x151; uint256 constant internal MM_TRACE_LENGTH = 0x152; uint256 constant internal MM_MAT10 = 0x153; uint256 constant internal MM_MAT11 = 0x154; uint256 constant internal MM_INPUT_VALUE_A = 0x155; uint256 constant internal MM_OUTPUT_VALUE_A = 0x156; uint256 constant internal MM_INPUT_VALUE_B = 0x157; uint256 constant internal MM_OUTPUT_VALUE_B = 0x158; uint256 constant internal MM_TRACE_GENERATOR = 0x159; uint256 constant internal MM_OODS_POINT = 0x15a; uint256 constant internal MM_COEFFICIENTS = 0x15b; // uint256[48] uint256 constant internal MM_OODS_VALUES = 0x18b; // uint256[22] uint256 constant internal MM_CONSTRAINT_POLY_ARGS_END = 0x1a1; uint256 constant internal MM_COMPOSITION_OODS_VALUES = 0x1a1; // uint256[2] uint256 constant internal MM_OODS_EVAL_POINTS = 0x1a3; // uint256[48] uint256 constant internal MM_OODS_COEFFICIENTS = 0x1d3; // uint256[24] uint256 constant internal MM_TRACE_QUERY_RESPONSES = 0x1eb; // uint256[960] uint256 constant internal MM_COMPOSITION_QUERY_RESPONSES = 0x5ab; // uint256[96] uint256 constant internal MM_CONTEXT_SIZE = 0x60b; } contract MerkleVerifier is IMerkleVerifier { function getHashMask() internal pure returns(uint256) { // Default implementation. return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000; } /* Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves. The inputs data sits in the queue at queuePtr. Each slot in the queue contains a 32 bytes leaf index and a 32 byte leaf value. The indices need to be in the range [N..2*N-1] and strictly incrementing. Decommitments are read from the channel in the ctx. The input data is destroyed during verification. */ function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash) { uint256 lhashMask = getHashMask(); require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES"); assembly { // queuePtr + i * 0x40 gives the i'th index in the queue. // hashesPtr + i * 0x40 gives the i'th hash in the queue. let hashesPtr := add(queuePtr, 0x20) let queueSize := mul(n, 0x40) let slotSize := 0x40 // The items are in slots [0, n-1]. let rdIdx := 0 let wrIdx := 0 // = n % n. // Iterate the queue until we hit the root. let index := mload(add(rdIdx, queuePtr)) let proofPtr := mload(channelPtr) // while(index > 1). for { } gt(index, 1) { } { let siblingIndex := xor(index, 1) // sibblingOffset := 0x20 * lsb(siblingIndex). let sibblingOffset := mulmod(siblingIndex, 0x20, 0x40) // Store the hash corresponding to index in the correct slot. // 0 if index is even and 0x20 if index is odd. // The hash of the sibling will be written to the other slot. mstore(xor(0x20, sibblingOffset), mload(add(rdIdx, hashesPtr))) rdIdx := addmod(rdIdx, slotSize, queueSize) // Inline channel operation: // Assume we are going to read a new hash from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let newHashPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Push index/2 into the queue, before reading the next index. // The order is important, as otherwise we may try to read from an empty queue (in // the case where we are working on one item). // wrIdx will be updated after writing the relevant hash to the queue. mstore(add(wrIdx, queuePtr), div(index, 2)) // Load the next index from the queue and check if it is our sibling. index := mload(add(rdIdx, queuePtr)) if eq(index, siblingIndex) { // Take sibling from queue rather than from proof. newHashPtr := add(rdIdx, hashesPtr) // Revert reading from proof. proofPtr := sub(proofPtr, 0x20) rdIdx := addmod(rdIdx, slotSize, queueSize) // Index was consumed, read the next one. // Note that the queue can't be empty at this point. // The index of the parent of the current node was already pushed into the // queue, and the parent is never the sibling. index := mload(add(rdIdx, queuePtr)) } mstore(sibblingOffset, mload(newHashPtr)) // Push the new hash to the end of the queue. mstore(add(wrIdx, hashesPtr), and(lhashMask, keccak256(0x00, 0x40))) wrIdx := addmod(wrIdx, slotSize, queueSize) } hash := mload(add(rdIdx, hashesPtr)) // Update the proof pointer in the context. mstore(channelPtr, proofPtr) } // emit LogBool(hash == root); require(hash == root, "INVALID_MERKLE_PROOF"); } } contract MimcConstraintPoly { // The Memory map during the execution of this contract is as follows: // [0x0, 0x20) - periodic_column/consts0_a. // [0x20, 0x40) - periodic_column/consts1_a. // [0x40, 0x60) - periodic_column/consts2_a. // [0x60, 0x80) - periodic_column/consts3_a. // [0x80, 0xa0) - periodic_column/consts4_a. // [0xa0, 0xc0) - periodic_column/consts5_a. // [0xc0, 0xe0) - periodic_column/consts6_a. // [0xe0, 0x100) - periodic_column/consts7_a. // [0x100, 0x120) - periodic_column/consts8_a. // [0x120, 0x140) - periodic_column/consts9_a. // [0x140, 0x160) - periodic_column/consts0_b. // [0x160, 0x180) - periodic_column/consts1_b. // [0x180, 0x1a0) - periodic_column/consts2_b. // [0x1a0, 0x1c0) - periodic_column/consts3_b. // [0x1c0, 0x1e0) - periodic_column/consts4_b. // [0x1e0, 0x200) - periodic_column/consts5_b. // [0x200, 0x220) - periodic_column/consts6_b. // [0x220, 0x240) - periodic_column/consts7_b. // [0x240, 0x260) - periodic_column/consts8_b. // [0x260, 0x280) - periodic_column/consts9_b. // [0x280, 0x2a0) - mat00. // [0x2a0, 0x2c0) - mat01. // [0x2c0, 0x2e0) - trace_length. // [0x2e0, 0x300) - mat10. // [0x300, 0x320) - mat11. // [0x320, 0x340) - input_value_a. // [0x340, 0x360) - output_value_a. // [0x360, 0x380) - input_value_b. // [0x380, 0x3a0) - output_value_b. // [0x3a0, 0x3c0) - trace_generator. // [0x3c0, 0x3e0) - oods_point. // [0x3e0, 0x9e0) - coefficients. // [0x9e0, 0xca0) - oods_values. // ----------------------- end of input data - ------------------------- // [0xca0, 0xcc0) - composition_degree_bound. // [0xcc0, 0xce0) - intermediate_value/after_lin_transform0_a_0. // [0xce0, 0xd00) - intermediate_value/after_lin_transform0_b_0. // [0xd00, 0xd20) - intermediate_value/after_lin_transform1_a_0. // [0xd20, 0xd40) - intermediate_value/after_lin_transform1_b_0. // [0xd40, 0xd60) - intermediate_value/after_lin_transform2_a_0. // [0xd60, 0xd80) - intermediate_value/after_lin_transform2_b_0. // [0xd80, 0xda0) - intermediate_value/after_lin_transform3_a_0. // [0xda0, 0xdc0) - intermediate_value/after_lin_transform3_b_0. // [0xdc0, 0xde0) - intermediate_value/after_lin_transform4_a_0. // [0xde0, 0xe00) - intermediate_value/after_lin_transform4_b_0. // [0xe00, 0xe20) - intermediate_value/after_lin_transform5_a_0. // [0xe20, 0xe40) - intermediate_value/after_lin_transform5_b_0. // [0xe40, 0xe60) - intermediate_value/after_lin_transform6_a_0. // [0xe60, 0xe80) - intermediate_value/after_lin_transform6_b_0. // [0xe80, 0xea0) - intermediate_value/after_lin_transform7_a_0. // [0xea0, 0xec0) - intermediate_value/after_lin_transform7_b_0. // [0xec0, 0xee0) - intermediate_value/after_lin_transform8_a_0. // [0xee0, 0xf00) - intermediate_value/after_lin_transform8_b_0. // [0xf00, 0xf20) - intermediate_value/after_lin_transform9_a_0. // [0xf20, 0xf40) - intermediate_value/after_lin_transform9_b_0. // [0xf40, 0xf80) - expmods. // [0xf80, 0xfe0) - denominator_invs. // [0xfe0, 0x1040) - denominators. // [0x1040, 0x1060) - numerators. // [0x1060, 0x10c0) - adjustments. // [0x10c0, 0x1180) - expmod_context. function() external { uint256 res; assembly { let PRIME := 0x30000003000000010000000000000001 // Copy input from calldata to memory. calldatacopy(0x0, 0x0, /*Input data size*/ 0xca0) let point := /*oods_point*/ mload(0x3c0) // Initialize composition_degree_bound to 2 * trace_length. mstore(0xca0, mul(2, /*trace_length*/ mload(0x2c0))) function expmod(base, exponent, modulus) -> res { let p := /*expmod_context*/ 0x10c0 mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } function degreeAdjustment(compositionPolynomialDegreeBound, constraintDegree, numeratorDegree, denominatorDegree) -> res { res := sub(sub(compositionPolynomialDegreeBound, 1), sub(add(constraintDegree, numeratorDegree), denominatorDegree)) } { // Prepare expmods for denominators and numerators. // expmods[0] = point^trace_length. mstore(0xf40, expmod(point, /*trace_length*/ mload(0x2c0), PRIME)) // expmods[1] = trace_generator^(trace_length - 1). mstore(0xf60, expmod(/*trace_generator*/ mload(0x3a0), sub(/*trace_length*/ mload(0x2c0), 1), PRIME)) } { // Prepare denominators for batch inverse. // Denominator for constraints: 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b', 'step9_a', 'step9_b'. // denominators[0] = point^trace_length - 1. mstore(0xfe0, addmod(/*point^trace_length*/ mload(0xf40), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'input_a', 'input_b'. // denominators[1] = point - 1. mstore(0x1000, addmod(point, sub(PRIME, 1), PRIME)) // Denominator for constraints: 'output_a', 'output_b'. // denominators[2] = point - trace_generator^(trace_length - 1). mstore(0x1020, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME)) } { // Compute the inverses of the denominators into denominatorInvs using batch inverse. // Start by computing the cumulative product. // Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop // denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of // d_0 * ... * d_{n-1}. // Compute the offset between the partialProducts array and the input values array. let productsToValuesOffset := 0x60 let prod := 1 let partialProductEndPtr := 0xfe0 for { let partialProductPtr := 0xf80 } lt(partialProductPtr, partialProductEndPtr) { partialProductPtr := add(partialProductPtr, 0x20) } { mstore(partialProductPtr, prod) // prod *= d_{i}. prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0xf80 // Compute the inverse of the product. let prodInv := expmod(prod, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := 0xfe0 for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } { // Compute numerators and adjustment polynomials. // Numerator for constraints 'step9_a', 'step9_b'. // numerators[0] = point - trace_generator^(trace_length - 1). mstore(0x1040, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME)) // Adjustment polynomial for constraints 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b'. // adjustments[0] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 0, trace_length). mstore(0x1060, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 0, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'step9_a', 'step9_b'. // adjustments[1] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 1, trace_length). mstore(0x1080, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 1, /*trace_length*/ mload(0x2c0)), PRIME)) // Adjustment polynomial for constraints 'input_a', 'output_a', 'input_b', 'output_b'. // adjustments[2] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, 1). mstore(0x10a0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), sub(/*trace_length*/ mload(0x2c0), 1), 0, 1), PRIME)) } { // Compute the result of the composition polynomial. { // after_lin_transform0_a_0 = mat00 * (column0_row0 - consts0_a) + mat01 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xcc0, val) } { // after_lin_transform0_b_0 = mat10 * (column0_row0 - consts0_a) + mat11 * (column10_row0 - consts0_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column0_row0*/ mload(0x9e0), sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column10_row0*/ mload(0xb40), sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)), PRIME), PRIME), PRIME) mstore(0xce0, val) } { // after_lin_transform1_a_0 = mat00 * (column1_row0 - consts1_a) + mat01 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd00, val) } { // after_lin_transform1_b_0 = mat10 * (column1_row0 - consts1_a) + mat11 * (column11_row0 - consts1_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column1_row0*/ mload(0xa20), sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column11_row0*/ mload(0xb80), sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)), PRIME), PRIME), PRIME) mstore(0xd20, val) } { // after_lin_transform2_a_0 = mat00 * (column2_row0 - consts2_a) + mat01 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd40, val) } { // after_lin_transform2_b_0 = mat10 * (column2_row0 - consts2_a) + mat11 * (column12_row0 - consts2_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column2_row0*/ mload(0xa40), sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column12_row0*/ mload(0xba0), sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)), PRIME), PRIME), PRIME) mstore(0xd60, val) } { // after_lin_transform3_a_0 = mat00 * (column3_row0 - consts3_a) + mat01 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xd80, val) } { // after_lin_transform3_b_0 = mat10 * (column3_row0 - consts3_a) + mat11 * (column13_row0 - consts3_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column3_row0*/ mload(0xa60), sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column13_row0*/ mload(0xbc0), sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)), PRIME), PRIME), PRIME) mstore(0xda0, val) } { // after_lin_transform4_a_0 = mat00 * (column4_row0 - consts4_a) + mat01 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xdc0, val) } { // after_lin_transform4_b_0 = mat10 * (column4_row0 - consts4_a) + mat11 * (column14_row0 - consts4_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column4_row0*/ mload(0xa80), sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column14_row0*/ mload(0xbe0), sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)), PRIME), PRIME), PRIME) mstore(0xde0, val) } { // after_lin_transform5_a_0 = mat00 * (column5_row0 - consts5_a) + mat01 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe00, val) } { // after_lin_transform5_b_0 = mat10 * (column5_row0 - consts5_a) + mat11 * (column15_row0 - consts5_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column5_row0*/ mload(0xaa0), sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column15_row0*/ mload(0xc00), sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)), PRIME), PRIME), PRIME) mstore(0xe20, val) } { // after_lin_transform6_a_0 = mat00 * (column6_row0 - consts6_a) + mat01 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe40, val) } { // after_lin_transform6_b_0 = mat10 * (column6_row0 - consts6_a) + mat11 * (column16_row0 - consts6_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column6_row0*/ mload(0xac0), sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column16_row0*/ mload(0xc20), sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)), PRIME), PRIME), PRIME) mstore(0xe60, val) } { // after_lin_transform7_a_0 = mat00 * (column7_row0 - consts7_a) + mat01 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xe80, val) } { // after_lin_transform7_b_0 = mat10 * (column7_row0 - consts7_a) + mat11 * (column17_row0 - consts7_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column7_row0*/ mload(0xae0), sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column17_row0*/ mload(0xc40), sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)), PRIME), PRIME), PRIME) mstore(0xea0, val) } { // after_lin_transform8_a_0 = mat00 * (column8_row0 - consts8_a) + mat01 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xec0, val) } { // after_lin_transform8_b_0 = mat10 * (column8_row0 - consts8_a) + mat11 * (column18_row0 - consts8_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column8_row0*/ mload(0xb00), sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column18_row0*/ mload(0xc60), sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)), PRIME), PRIME), PRIME) mstore(0xee0, val) } { // after_lin_transform9_a_0 = mat00 * (column9_row0 - consts9_a) + mat01 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat00*/ mload(0x280), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat01*/ mload(0x2a0), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf00, val) } { // after_lin_transform9_b_0 = mat10 * (column9_row0 - consts9_a) + mat11 * (column19_row0 - consts9_b). let val := addmod( mulmod( /*mat10*/ mload(0x2e0), addmod( /*column9_row0*/ mload(0xb20), sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)), PRIME), PRIME), mulmod( /*mat11*/ mload(0x300), addmod( /*column19_row0*/ mload(0xc80), sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)), PRIME), PRIME), PRIME) mstore(0xf20, val) } { // Constraint expression for step0_a: column1_row0 - after_lin_transform0_a_0 * after_lin_transform0_a_0 * after_lin_transform0_a_0. let val := addmod( /*column1_row0*/ mload(0xa20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME), /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[0] + coefficients[1] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x3e0), mulmod(/*coefficients[1]*/ mload(0x400), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step0_b: column11_row0 - after_lin_transform0_b_0 * after_lin_transform0_b_0 * after_lin_transform0_b_0. let val := addmod( /*column11_row0*/ mload(0xb80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME), /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[2] + coefficients[3] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[2]*/ mload(0x420), mulmod(/*coefficients[3]*/ mload(0x440), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_a: column2_row0 - after_lin_transform1_a_0 * after_lin_transform1_a_0 * after_lin_transform1_a_0. let val := addmod( /*column2_row0*/ mload(0xa40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME), /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[4] + coefficients[5] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[4]*/ mload(0x460), mulmod(/*coefficients[5]*/ mload(0x480), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step1_b: column12_row0 - after_lin_transform1_b_0 * after_lin_transform1_b_0 * after_lin_transform1_b_0. let val := addmod( /*column12_row0*/ mload(0xba0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME), /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[6] + coefficients[7] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[6]*/ mload(0x4a0), mulmod(/*coefficients[7]*/ mload(0x4c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_a: column3_row0 - after_lin_transform2_a_0 * after_lin_transform2_a_0 * after_lin_transform2_a_0. let val := addmod( /*column3_row0*/ mload(0xa60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME), /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[8] + coefficients[9] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[8]*/ mload(0x4e0), mulmod(/*coefficients[9]*/ mload(0x500), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step2_b: column13_row0 - after_lin_transform2_b_0 * after_lin_transform2_b_0 * after_lin_transform2_b_0. let val := addmod( /*column13_row0*/ mload(0xbc0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME), /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[10] + coefficients[11] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[10]*/ mload(0x520), mulmod(/*coefficients[11]*/ mload(0x540), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_a: column4_row0 - after_lin_transform3_a_0 * after_lin_transform3_a_0 * after_lin_transform3_a_0. let val := addmod( /*column4_row0*/ mload(0xa80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME), /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[12] + coefficients[13] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x560), mulmod(/*coefficients[13]*/ mload(0x580), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step3_b: column14_row0 - after_lin_transform3_b_0 * after_lin_transform3_b_0 * after_lin_transform3_b_0. let val := addmod( /*column14_row0*/ mload(0xbe0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME), /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[14] + coefficients[15] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[14]*/ mload(0x5a0), mulmod(/*coefficients[15]*/ mload(0x5c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_a: column5_row0 - after_lin_transform4_a_0 * after_lin_transform4_a_0 * after_lin_transform4_a_0. let val := addmod( /*column5_row0*/ mload(0xaa0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME), /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[16] + coefficients[17] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[16]*/ mload(0x5e0), mulmod(/*coefficients[17]*/ mload(0x600), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step4_b: column15_row0 - after_lin_transform4_b_0 * after_lin_transform4_b_0 * after_lin_transform4_b_0. let val := addmod( /*column15_row0*/ mload(0xc00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME), /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[18] + coefficients[19] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[18]*/ mload(0x620), mulmod(/*coefficients[19]*/ mload(0x640), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_a: column6_row0 - after_lin_transform5_a_0 * after_lin_transform5_a_0 * after_lin_transform5_a_0. let val := addmod( /*column6_row0*/ mload(0xac0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME), /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[20] + coefficients[21] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[20]*/ mload(0x660), mulmod(/*coefficients[21]*/ mload(0x680), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step5_b: column16_row0 - after_lin_transform5_b_0 * after_lin_transform5_b_0 * after_lin_transform5_b_0. let val := addmod( /*column16_row0*/ mload(0xc20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME), /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[22] + coefficients[23] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[22]*/ mload(0x6a0), mulmod(/*coefficients[23]*/ mload(0x6c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_a: column7_row0 - after_lin_transform6_a_0 * after_lin_transform6_a_0 * after_lin_transform6_a_0. let val := addmod( /*column7_row0*/ mload(0xae0), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME), /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[24] + coefficients[25] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[24]*/ mload(0x6e0), mulmod(/*coefficients[25]*/ mload(0x700), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step6_b: column17_row0 - after_lin_transform6_b_0 * after_lin_transform6_b_0 * after_lin_transform6_b_0. let val := addmod( /*column17_row0*/ mload(0xc40), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME), /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[26] + coefficients[27] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[26]*/ mload(0x720), mulmod(/*coefficients[27]*/ mload(0x740), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_a: column8_row0 - after_lin_transform7_a_0 * after_lin_transform7_a_0 * after_lin_transform7_a_0. let val := addmod( /*column8_row0*/ mload(0xb00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME), /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[28] + coefficients[29] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[28]*/ mload(0x760), mulmod(/*coefficients[29]*/ mload(0x780), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step7_b: column18_row0 - after_lin_transform7_b_0 * after_lin_transform7_b_0 * after_lin_transform7_b_0. let val := addmod( /*column18_row0*/ mload(0xc60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME), /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[30] + coefficients[31] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[30]*/ mload(0x7a0), mulmod(/*coefficients[31]*/ mload(0x7c0), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_a: column9_row0 - after_lin_transform8_a_0 * after_lin_transform8_a_0 * after_lin_transform8_a_0. let val := addmod( /*column9_row0*/ mload(0xb20), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME), /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[32] + coefficients[33] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[32]*/ mload(0x7e0), mulmod(/*coefficients[33]*/ mload(0x800), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step8_b: column19_row0 - after_lin_transform8_b_0 * after_lin_transform8_b_0 * after_lin_transform8_b_0. let val := addmod( /*column19_row0*/ mload(0xc80), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME), /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[34] + coefficients[35] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[34]*/ mload(0x820), mulmod(/*coefficients[35]*/ mload(0x840), /*adjustments[0]*/mload(0x1060), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_a: column0_row1 - after_lin_transform9_a_0 * after_lin_transform9_a_0 * after_lin_transform9_a_0. let val := addmod( /*column0_row1*/ mload(0xa00), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME), /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[36] + coefficients[37] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[36]*/ mload(0x860), mulmod(/*coefficients[37]*/ mload(0x880), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for step9_b: column10_row1 - after_lin_transform9_b_0 * after_lin_transform9_b_0 * after_lin_transform9_b_0. let val := addmod( /*column10_row1*/ mload(0xb60), sub( PRIME, mulmod( mulmod( /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME), /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[0]. val := mulmod(val, mload(0x1040), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0xf80), PRIME) // res += val * (coefficients[38] + coefficients[39] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[38]*/ mload(0x8a0), mulmod(/*coefficients[39]*/ mload(0x8c0), /*adjustments[1]*/mload(0x1080), PRIME)), PRIME), PRIME) } { // Constraint expression for input_a: column0_row0 - input_value_a. let val := addmod(/*column0_row0*/ mload(0x9e0), sub(PRIME, /*input_value_a*/ mload(0x320)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[40] + coefficients[41] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[40]*/ mload(0x8e0), mulmod(/*coefficients[41]*/ mload(0x900), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_a: column9_row0 - output_value_a. let val := addmod(/*column9_row0*/ mload(0xb20), sub(PRIME, /*output_value_a*/ mload(0x340)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[42] + coefficients[43] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[42]*/ mload(0x920), mulmod(/*coefficients[43]*/ mload(0x940), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for input_b: column10_row0 - input_value_b. let val := addmod(/*column10_row0*/ mload(0xb40), sub(PRIME, /*input_value_b*/ mload(0x360)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[1]. val := mulmod(val, mload(0xfa0), PRIME) // res += val * (coefficients[44] + coefficients[45] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[44]*/ mload(0x960), mulmod(/*coefficients[45]*/ mload(0x980), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } { // Constraint expression for output_b: column19_row0 - output_value_b. let val := addmod(/*column19_row0*/ mload(0xc80), sub(PRIME, /*output_value_b*/ mload(0x380)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[2]. val := mulmod(val, mload(0xfc0), PRIME) // res += val * (coefficients[46] + coefficients[47] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[46]*/ mload(0x9a0), mulmod(/*coefficients[47]*/ mload(0x9c0), /*adjustments[2]*/mload(0x10a0), PRIME)), PRIME), PRIME) } mstore(0, res) return(0, 0x20) } } } } contract PeriodicColumnContract { function compute(uint256 x) external pure returns (uint256 result); } contract PrimeFieldElement6 { uint256 internal constant K_MODULUS = 0x30000003000000010000000000000001; uint256 internal constant K_MODULUS_MASK = 0x3fffffffffffffffffffffffffffffff; uint256 internal constant K_MONTGOMERY_R = 0xffffff0fffffffafffffffffffffffb; uint256 internal constant K_MONTGOMERY_R_INV = 0x9000001200000096000000600000001; uint256 internal constant GENERATOR_VAL = 3; uint256 internal constant ONE_VAL = 1; uint256 internal constant GEN1024_VAL = 0x2361be682e1cc2d366e86e194024739f; function fromMontgomery(uint256 val) internal pure returns (uint256 res) { // uint256 res = fmul(val, kMontgomeryRInv); assembly { res := mulmod( val, 0x9000001200000096000000600000001, 0x30000003000000010000000000000001 ) } return res; } function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) { // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field // element. uint256 res = uint256(bs); return fromMontgomery(res); } function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) { //uint256 res = fmul(val, kMontgomeryR); assembly { res := mulmod( val, 0xffffff0fffffffafffffffffffffffb, 0x30000003000000010000000000000001 ) } return res; } function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { //uint256 res = mulmod(a, b, kModulus); assembly { res := mulmod(a, b, 0x30000003000000010000000000000001) } return res; } function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, b, kModulus); assembly { res := addmod(a, b, 0x30000003000000010000000000000001) } return res; } function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, kModulus - b, kModulus); assembly { res := addmod( a, sub(0x30000003000000010000000000000001, b), 0x30000003000000010000000000000001 ) } return res; } function fpow(uint256 val, uint256 exp) internal returns (uint256) { return expmod(val, exp, K_MODULUS); } function expmod(uint256 base, uint256 exponent, uint256 modulus) internal returns (uint256 res) { assembly { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } } function inverse(uint256 val) internal returns (uint256) { return expmod(val, K_MODULUS - 2, K_MODULUS); } } contract Prng is PrimeFieldElement6 { function storePrng(uint256 statePtr, bytes32 digest, uint256 counter) internal pure { assembly { mstore(statePtr, digest) mstore(add(statePtr, 0x20), counter) } } function loadPrng(uint256 statePtr) internal pure returns (bytes32, uint256) { bytes32 digest; uint256 counter; assembly { digest := mload(statePtr) counter := mload(add(statePtr, 0x20)) } return (digest, counter); } function initPrng(uint256 prngPtr, bytes32 publicInputHash) internal pure { storePrng(prngPtr, /*keccak256(publicInput)*/ publicInputHash, 0); } /* Auxiliary function for getRandomBytes. */ function getRandomBytesInner(bytes32 digest, uint256 counter) internal pure returns (bytes32, uint256, bytes32) { // returns 32 bytes (for random field elements or four queries at a time). bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter)); return (digest, counter + 1, randomBytes); } /* Returns 32 bytes. Used for a random field element, or for 4 query indices. */ function getRandomBytes(uint256 prngPtr) internal pure returns (bytes32 randomBytes) { bytes32 digest; uint256 counter; (digest, counter) = loadPrng(prngPtr); // returns 32 bytes (for random field elements or four queries at a time). (digest, counter, randomBytes) = getRandomBytesInner(digest, counter); storePrng(prngPtr, digest, counter); return randomBytes; } function mixSeedWithBytes(uint256 prngPtr, bytes memory dataBytes) internal pure { bytes32 digest; assembly { digest := mload(prngPtr) } initPrng(prngPtr, keccak256(abi.encodePacked(digest, dataBytes))); } function getPrngDigest(uint256 prngPtr) internal pure returns (bytes32 digest) { assembly { digest := mload(prngPtr) } } } contract PublicInputOffsets { // The following constants are offsets of data expected in the public input. uint256 internal constant OFFSET_LOG_TRACE_LENGTH = 0; uint256 internal constant OFFSET_VDF_OUTPUT_X = 1; uint256 internal constant OFFSET_VDF_OUTPUT_Y = 2; uint256 internal constant OFFSET_VDF_INPUT_X = 3; uint256 internal constant OFFSET_VDF_INPUT_Y = 4; // The Verifier derives the number of iterations from the log of the trace length. // The Vending contract uses the number of iterations. uint256 internal constant OFFSET_N_ITER = 0; } contract StarkParameters is PrimeFieldElement6 { uint256 constant internal N_COEFFICIENTS = 48; uint256 constant internal MASK_SIZE = 22; uint256 constant internal N_ROWS_IN_MASK = 2; uint256 constant internal N_COLUMNS_IN_MASK = 20; uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; uint256 constant internal MAX_FRI_STEP = 3; } contract VerifierChannel is Prng { /* We store the state of the channel in uint256[3] as follows: [0] proof pointer. [1] prng digest. [2] prng counter. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; event LogValue(bytes32 val); event SendRandomnessEvent(uint256 val); event ReadFieldElementEvent(uint256 val); event ReadHashEvent(bytes32 val); function getPrngPtr(uint256 channelPtr) internal pure returns (uint256) { return channelPtr + 0x20; } function initChannel(uint256 channelPtr, uint256 proofPtr, bytes32 publicInputHash) internal pure { assembly { // Skip 0x20 bytes length at the beginning of the proof. mstore(channelPtr, add(proofPtr, 0x20)) } initPrng(getPrngPtr(channelPtr), publicInputHash); } function sendFieldElements(uint256 channelPtr, uint256 nElements, uint256 targetPtr) internal pure { require(nElements < 0x1000000, "Overflow protection failed."); assembly { let PRIME := 0x30000003000000010000000000000001 let PRIME_MON_R_INV := 0x9000001200000096000000600000001 let PRIME_MASK := 0x3fffffffffffffffffffffffffffffff let digestPtr := add(channelPtr, 0x20) let counterPtr := add(channelPtr, 0x40) let endPtr := add(targetPtr, mul(nElements, 0x20)) for { } lt(targetPtr, endPtr) { targetPtr := add(targetPtr, 0x20) } { // *targetPtr = getRandomFieldElement(getPrngPtr(channelPtr)); let fieldElement := PRIME // while (fieldElement >= PRIME). for { } iszero(lt(fieldElement, PRIME)) { } { // keccak256(abi.encodePacked(digest, counter)); fieldElement := and(keccak256(digestPtr, 0x40), PRIME_MASK) // *counterPtr += 1; mstore(counterPtr, add(mload(counterPtr), 1)) } // *targetPtr = fromMontgomery(fieldElement); mstore(targetPtr, mulmod(fieldElement, PRIME_MON_R_INV, PRIME)) // emit ReadFieldElementEvent(fieldElement); // log1(targetPtr, 0x20, 0x4bfcc54f35095697be2d635fb0706801e13637312eff0cedcdfc254b3b8c385e); } } } /* Sends random queries and returns an array of queries sorted in ascending order. Generates count queries in the range [0, mask] and returns the number of unique queries. Note that mask is of the form 2^k-1 (for some k). Note that queriesOutPtr may be (and is) inteleaved with other arrays. The stride parameter is passed to indicate the distance between every two entries to the queries array, i.e. stride = 0x20*(number of interleaved arrays). */ function sendRandomQueries( uint256 channelPtr, uint256 count, uint256 mask, uint256 queriesOutPtr, uint256 stride) internal pure returns (uint256) { uint256 val; uint256 shift = 0; uint256 endPtr = queriesOutPtr; for (uint256 i = 0; i < count; i++) { if (shift == 0) { val = uint256(getRandomBytes(getPrngPtr(channelPtr))); shift = 0x100; } shift -= 0x40; uint256 queryIdx = (val >> shift) & mask; // emit sendRandomnessEvent(queryIdx); uint256 ptr = endPtr; uint256 curr; // Insert new queryIdx in the correct place like insertion sort. while (ptr > queriesOutPtr) { assembly { curr := mload(sub(ptr, stride)) } if (queryIdx >= curr) { break; } assembly { mstore(ptr, curr) } ptr -= stride; } if (queryIdx != curr) { assembly { mstore(ptr, queryIdx) } endPtr += stride; } else { // Revert right shuffling. while (ptr < endPtr) { assembly { mstore(ptr, mload(add(ptr, stride))) ptr := add(ptr, stride) } } } } return (endPtr - queriesOutPtr) / stride; } function readBytes(uint256 channelPtr, bool mix) internal pure returns (bytes32) { uint256 proofPtr; bytes32 val; assembly { proofPtr := mload(channelPtr) val := mload(proofPtr) mstore(channelPtr, add(proofPtr, 0x20)) } if (mix) { // inline: Prng.mixSeedWithBytes(getPrngPtr(channelPtr), abi.encodePacked(val)); assembly { let digestPtr := add(channelPtr, 0x20) let counterPtr := add(digestPtr, 0x20) mstore(counterPtr, val) // prng.digest := keccak256(digest||val), nonce was written earlier. mstore(digestPtr, keccak256(digestPtr, 0x40)) // prng.counter := 0. mstore(counterPtr, 0) } } return val; } function readHash(uint256 channelPtr, bool mix) internal pure returns (bytes32) { bytes32 val = readBytes(channelPtr, mix); // emit ReadHashEvent(val); return val; } function readFieldElement(uint256 channelPtr, bool mix) internal pure returns (uint256) { uint256 val = fromMontgomery(uint256(readBytes(channelPtr, mix))); // emit ReadFieldElementEvent(val); return val; } function verifyProofOfWork(uint256 channelPtr, uint256 proofOfWorkBits) internal pure { if (proofOfWorkBits == 0) { return; } uint256 proofOfWorkDigest; assembly { // [0:29] := 0123456789abcded || digest || workBits. mstore(0, 0x0123456789abcded000000000000000000000000000000000000000000000000) let digest := mload(add(channelPtr, 0x20)) mstore(0x8, digest) mstore8(0x28, proofOfWorkBits) mstore(0, keccak256(0, 0x29)) let proofPtr := mload(channelPtr) mstore(0x20, mload(proofPtr)) // proofOfWorkDigest:= keccak256(keccak256(0123456789abcded || digest || workBits) || nonce). proofOfWorkDigest := keccak256(0, 0x28) mstore(0, digest) // prng.digest := keccak256(digest||nonce), nonce was written earlier. mstore(add(channelPtr, 0x20), keccak256(0, 0x28)) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) mstore(channelPtr, add(proofPtr, 0x8)) } uint256 proofOfWorkThreshold = uint256(1) << (256 - proofOfWorkBits); require(proofOfWorkDigest < proofOfWorkThreshold, "Proof of work check failed."); } } contract FactRegistry is IQueryableFactRegistry { // Mapping: fact hash -> true. mapping (bytes32 => bool) private verifiedFact; // Indicates whether the Fact Registry has at least one fact registered. bool anyFactRegistered; /* Checks if a fact has been verified. */ function isValid(bytes32 fact) external view returns(bool) { return verifiedFact[fact]; } function registerFact( bytes32 factHash ) internal { // This function stores the testiment hash in the mapping. verifiedFact[factHash] = true; // Mark first time off. if (!anyFactRegistered) { anyFactRegistered = true; } } /* Indicates whether at least one fact was registered. */ function hasRegisteredFact() external view returns(bool) { return anyFactRegistered; } } contract FriLayer is MerkleVerifier, PrimeFieldElement6 { event LogGas(string name, uint256 val); uint256 constant internal FRI_MAX_FRI_STEP = 4; uint256 constant internal MAX_COSET_SIZE = 2**FRI_MAX_FRI_STEP; // Generator of the group of size MAX_COSET_SIZE: GENERATOR_VAL**((PRIME - 1)/MAX_COSET_SIZE). uint256 constant internal FRI_GROUP_GEN = 0x1388a7fd3b4b9599dc4b0691d6a5fcba; uint256 constant internal FRI_GROUP_SIZE = 0x20 * MAX_COSET_SIZE; uint256 constant internal FRI_CTX_TO_COSET_EVALUATIONS_OFFSET = 0; uint256 constant internal FRI_CTX_TO_FRI_GROUP_OFFSET = FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET = FRI_CTX_TO_FRI_GROUP_OFFSET + FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_SIZE = FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET + (FRI_GROUP_SIZE / 2); function nextLayerElementFromTwoPreviousLayerElements( uint256 fX, uint256 fMinusX, uint256 evalPoint, uint256 xInv) internal pure returns (uint256 res) { // Folding formula: // f(x) = g(x^2) + xh(x^2) // f(-x) = g((-x)^2) - xh((-x)^2) = g(x^2) - xh(x^2) // => // 2g(x^2) = f(x) + f(-x) // 2h(x^2) = (f(x) - f(-x))/x // => The 2*interpolation at evalPoint is: // 2*(g(x^2) + evalPoint*h(x^2)) = f(x) + f(-x) + evalPoint*(f(x) - f(-x))*xInv. // // Note that multiplying by 2 doesn't affect the degree, // so we can just agree to do that on both the prover and verifier. assembly { // PRIME is PrimeFieldElement6.K_MODULUS. let PRIME := 0x30000003000000010000000000000001 // Note that whenever we call add(), the result is always less than 2*PRIME, // so there are no overflows. res := addmod(add(fX, fMinusX), mulmod(mulmod(evalPoint, xInv, PRIME), add(fX, /*-fMinusX*/sub(PRIME, fMinusX)), PRIME), PRIME) } } /* Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element. FRI layer n: f0 f1 f2 f3 ----------------------------------------- \ / -- \ / ----------- FRI layer n+1: f0 f2 -------------------------------------------- \ ---/ ------------- FRI layer n+2: f0 The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements(). */ function do2FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x30000003000000010000000000000001 let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let f0 := mload(evaluationsOnCosetPtr) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) f2 := addmod(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(mload(add(friHalfInvGroupPtr, 0x20)), friEvalPointDivByX, PRIME), PRIME), PRIME) } { let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME) nextXInv := mulmod(newXInv, newXInv, PRIME) } // f0 + f2 < 4P ( = 3 + 1). nextLayerValue := addmod(add(f0, f2), mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME), add(f0, /*-fMinusX*/sub(PRIME, f2)), PRIME), PRIME) } } /* Reads 8 elements, and applies 4 + 2 + 1 FRI transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do3FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0, f4 < 7P -> f0 + f4 < 14P && 9P < f0 + (MPRIME - f4) < 23P. nextLayerValue := addmod(add(f0, f4), mulmod(mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) nextXInv := mulmod(xInv4, xInv4, PRIME) } } } /* This function reads 16 elements, and applies 8 + 4 + 2 + 1 fri transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do4FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let friEvalPointDivByXTessed let PRIME := 0x30000003000000010000000000000001 let MPRIME := 0x300000030000000100000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } { let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) friEvalPointDivByXTessed := mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME) // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0 < 15P ( = 7 + 7 + 1). f0 := add(add(f0, f4), mulmod(friEvalPointDivByXTessed, add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME)) } { let f8 := mload(add(evaluationsOnCosetPtr, 0x100)) { let friEvalPointDivByX4 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x80)), PRIME) { let f9 := mload(add(evaluationsOnCosetPtr, 0x120)) // f8 < 3P ( = 1 + 1 + 1). f8 := add(add(f8, f9), mulmod(friEvalPointDivByX4, add(f8, /*-fMinusX*/sub(PRIME, f9)), PRIME)) } let f10 := mload(add(evaluationsOnCosetPtr, 0x140)) { let f11 := mload(add(evaluationsOnCosetPtr, 0x160)) // f10 < 3P ( = 1 + 1 + 1). f10 := add(add(f10, f11), mulmod(add(f10, /*-fMinusX*/sub(PRIME, f11)), // friEvalPointDivByX4 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xa0)). mulmod(friEvalPointDivByX4, imaginaryUnit, PRIME), PRIME)) } // f8 < 7P ( = 3 + 3 + 1). f8 := add(add(f8, f10), mulmod(mulmod(friEvalPointDivByX4, friEvalPointDivByX4, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f10)), PRIME)) } { let f12 := mload(add(evaluationsOnCosetPtr, 0x180)) { let friEvalPointDivByX6 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0xc0)), PRIME) { let f13 := mload(add(evaluationsOnCosetPtr, 0x1a0)) // f12 < 3P ( = 1 + 1 + 1). f12 := add(add(f12, f13), mulmod(friEvalPointDivByX6, add(f12, /*-fMinusX*/sub(PRIME, f13)), PRIME)) } let f14 := mload(add(evaluationsOnCosetPtr, 0x1c0)) { let f15 := mload(add(evaluationsOnCosetPtr, 0x1e0)) // f14 < 3P ( = 1 + 1 + 1). f14 := add(add(f14, f15), mulmod(add(f14, /*-fMinusX*/sub(PRIME, f15)), // friEvalPointDivByX6 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xe0)). mulmod(friEvalPointDivByX6, imaginaryUnit, PRIME), PRIME)) } // f12 < 7P ( = 3 + 3 + 1). f12 := add(add(f12, f14), mulmod(mulmod(friEvalPointDivByX6, friEvalPointDivByX6, PRIME), add(f12, /*-fMinusX*/sub(MPRIME, f14)), PRIME)) } // f8 < 15P ( = 7 + 7 + 1). f8 := add(add(f8, f12), mulmod(mulmod(friEvalPointDivByXTessed, imaginaryUnit, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f12)), PRIME)) } // f0, f8 < 15P -> f0 + f8 < 30P && 16P < f0 + (MPRIME - f8) < 31P. nextLayerValue := addmod(add(f0, f8), mulmod(mulmod(friEvalPointDivByXTessed, friEvalPointDivByXTessed, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f8)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) let xInv8 := mulmod(xInv4, xInv4, PRIME) nextXInv := mulmod(xInv8, xInv8, PRIME) } } } /* Gathers the "cosetSize" elements that belong to the same coset as the item at the top of the FRI queue and stores them in ctx[MM_FRI_STEP_VALUES:]. Returns friQueueHead - friQueueHead_ + 0x60 * (# elements that were taken from the queue). cosetIdx - the start index of the coset that was gathered. cosetOffset_ - the xInv field element that corresponds to cosetIdx. */ function gatherCosetInputs( uint256 channelPtr, uint256 friCtx, uint256 friQueueHead_, uint256 cosetSize) internal pure returns (uint256 friQueueHead, uint256 cosetIdx, uint256 cosetOffset_) { uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; friQueueHead = friQueueHead_; assembly { let queueItemIdx := mload(friQueueHead) // The coset index is represented by the most significant bits of the queue item index. cosetIdx := and(queueItemIdx, not(sub(cosetSize, 1))) let nextCosetIdx := add(cosetIdx, cosetSize) let PRIME := 0x30000003000000010000000000000001 // Get the algebraic coset offset: // I.e. given c*g^(-k) compute c, where // g is the generator of the coset group. // k is bitReverse(offsetWithinCoset, log2(cosetSize)). // // To do this we multiply the algebraic coset offset at the top of the queue (c*g^(-k)) // by the group element that corresponds to the index inside the coset (g^k). cosetOffset_ := mulmod( /*(c*g^(-k)*/ mload(add(friQueueHead, 0x40)), /*(g^k)*/ mload(add(friGroupPtr, mul(/*offsetWithinCoset*/sub(queueItemIdx, cosetIdx), 0x20))), PRIME) let proofPtr := mload(channelPtr) for { let index := cosetIdx } lt(index, nextCosetIdx) { index := add(index, 1) } { // Inline channel operation: // Assume we are going to read the next element from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let fieldElementPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Load the next index from the queue and check if it is our sibling. if eq(index, queueItemIdx) { // Take element from the queue rather than from the proof // and convert it back to Montgomery form for Merkle verification. fieldElementPtr := add(friQueueHead, 0x20) // Revert the read from proof. proofPtr := sub(proofPtr, 0x20) // Reading the next index here is safe due to the // delimiter after the queries. friQueueHead := add(friQueueHead, 0x60) queueItemIdx := mload(friQueueHead) } // Note that we apply the modulo operation to convert the field elements we read // from the proof to canonical representation (in the range [0, PRIME - 1]). mstore(evaluationsOnCosetPtr, mod(mload(fieldElementPtr), PRIME)) evaluationsOnCosetPtr := add(evaluationsOnCosetPtr, 0x20) } mstore(channelPtr, proofPtr) } } /* Returns the bit reversal of num assuming it has the given number of bits. For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101, the function will return (0b)101100. */ function bitReverse(uint256 num, uint256 numberOfBits) internal pure returns(uint256 numReversed) { assert((numberOfBits == 256) || (num < 2 ** numberOfBits)); uint256 n = num; uint256 r = 0; for (uint256 k = 0; k < numberOfBits; k++) { r = (r * 2) | (n % 2); n = n / 2; } return r; } /* Initializes the FRI group and half inv group in the FRI context. */ function initFriGroups(uint256 friCtx) internal { uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // FRI_GROUP_GEN is the coset generator. // Raising it to the (MAX_COSET_SIZE - 1) power gives us the inverse. uint256 genFriGroup = FRI_GROUP_GEN; uint256 genFriGroupInv = fpow(genFriGroup, (MAX_COSET_SIZE - 1)); uint256 lastVal = ONE_VAL; uint256 lastValInv = ONE_VAL; uint256 prime = PrimeFieldElement6.K_MODULUS; assembly { // ctx[mmHalfFriInvGroup + 0] = ONE_VAL; mstore(friHalfInvGroupPtr, lastValInv) // ctx[mmFriGroup + 0] = ONE_VAL; mstore(friGroupPtr, lastVal) // ctx[mmFriGroup + 1] = fsub(0, ONE_VAL); mstore(add(friGroupPtr, 0x20), sub(prime, lastVal)) } // To compute [1, -1 (== g^n/2), g^n/4, -g^n/4, ...] // we compute half the elements and derive the rest using negation. uint256 halfCosetSize = MAX_COSET_SIZE / 2; for (uint256 i = 1; i < halfCosetSize; i++) { lastVal = fmul(lastVal, genFriGroup); lastValInv = fmul(lastValInv, genFriGroupInv); uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1); assembly { // ctx[mmHalfFriInvGroup + idx] = lastValInv; mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv) // ctx[mmFriGroup + 2*idx] = lastVal; mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal) // ctx[mmFriGroup + 2*idx + 1] = fsub(0, lastVal); mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal)) } } } /* Operates on the coset of size friFoldedCosetSize that start at index. It produces 3 outputs: 1. The field elements that result from doing FRI reductions on the coset. 2. The pointInv elements for the location that corresponds to the first output. 3. The root of a Merkle tree for the input layer. The input is read either from the queue or from the proof depending on data availability. Since the function reads from the queue it returns an updated head pointer. */ function doFriSteps( uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint, uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr) internal pure { uint256 friValue; uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // Compare to expected FRI step sizes in order of likelihood, step size 3 being most common. if (friCosetSize == 8) { (friValue, cosetOffset_) = do3FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 4) { (friValue, cosetOffset_) = do2FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 16) { (friValue, cosetOffset_) = do4FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else { require(false, "Only step sizes of 2, 3 or 4 are supported."); } uint256 lhashMask = getHashMask(); assembly { let indexInNextStep := div(index, friCosetSize) mstore(merkleQueuePtr, indexInNextStep) mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr, mul(0x20,friCosetSize)))) mstore(friQueueTail, indexInNextStep) mstore(add(friQueueTail, 0x20), friValue) mstore(add(friQueueTail, 0x40), cosetOffset_) } } /* Computes the FRI step with eta = log2(friCosetSize) for all the live queries. The input and output data is given in array of triplets: (query index, FRI value, FRI inversed point) in the address friQueuePtr (which is &ctx[mmFriQueue:]). The function returns the number of live queries remaining after computing the FRI step. The number of live queries decreases whenever multiple query points in the same coset are reduced to a single query in the next FRI layer. As the function computes the next layer it also collects that data from the previous layer for Merkle verification. */ function computeNextLayer( uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries, uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx) internal pure returns (uint256 nLiveQueries) { uint256 merkleQueueTail = merkleQueuePtr; uint256 friQueueHead = friQueuePtr; uint256 friQueueTail = friQueuePtr; uint256 friQueueEnd = friQueueHead + (0x60 * nQueries); do { uint256 cosetOffset; uint256 index; (friQueueHead, index, cosetOffset) = gatherCosetInputs( channelPtr, friCtx, friQueueHead, friCosetSize); doFriSteps( friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index, merkleQueueTail); merkleQueueTail += 0x40; friQueueTail += 0x60; } while (friQueueHead < friQueueEnd); return (friQueueTail - friQueuePtr) / 0x60; } } contract HornerEvaluator is PrimeFieldElement6 { /* Computes the evaluation of a polynomial f(x) = sum(a_i * x^i) on the given point. The coefficients of the polynomial are given in a_0 = coefsStart[0], ..., a_{n-1} = coefsStart[n - 1] where n = nCoefs = friLastLayerDegBound. Note that coefsStart is not actually an array but a direct pointer. The function requires that n is divisible by 8. */ function hornerEval(uint256 coefsStart, uint256 point, uint256 nCoefs) internal pure returns (uint256) { uint256 result = 0; uint256 prime = PrimeFieldElement6.K_MODULUS; require(nCoefs % 8 == 0, "Number of polynomial coefficients must be divisible by 8"); require(nCoefs < 4096, "No more than 4096 coefficients are supported"); assembly { let coefsPtr := add(coefsStart, mul(nCoefs, 0x20)) for { } gt(coefsPtr, coefsStart) { } { // Reduce coefsPtr by 8 field elements. coefsPtr := sub(coefsPtr, 0x100) // Apply 4 Horner steps (result := result * point + coef). result := add(mload(add(coefsPtr, 0x80)), mulmod( add(mload(add(coefsPtr, 0xa0)), mulmod( add(mload(add(coefsPtr, 0xc0)), mulmod( add(mload(add(coefsPtr, 0xe0)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) // Apply 4 additional Horner steps. result := add(mload(coefsPtr), mulmod( add(mload(add(coefsPtr, 0x20)), mulmod( add(mload(add(coefsPtr, 0x40)), mulmod( add(mload(add(coefsPtr, 0x60)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) } } // Since the last operation was "add" (instead of "addmod"), we need to take result % prime. return result % prime; } } contract MemoryAccessUtils is MemoryMap { function getPtr(uint256[] memory ctx, uint256 offset) internal pure returns (uint256) { uint256 ctxPtr; require(offset < MM_CONTEXT_SIZE, "Overflow protection failed"); assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + offset * 0x20; } function getProofPtr(uint256[] memory proof) internal pure returns (uint256) { uint256 proofPtr; assembly { proofPtr := proof } return proofPtr; } function getChannelPtr(uint256[] memory ctx) internal pure returns (uint256) { uint256 ctxPtr; assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + MM_CHANNEL * 0x20; } function getQueries(uint256[] memory ctx) internal pure returns (uint256[] memory) { uint256[] memory queries; // Dynamic array holds length followed by values. uint256 offset = 0x20 + 0x20*MM_N_UNIQUE_QUERIES; assembly { queries := add(ctx, offset) } return queries; } function getMerkleQueuePtr(uint256[] memory ctx) internal pure returns (uint256) { return getPtr(ctx, MM_MERKLE_QUEUE); } function getFriSteps(uint256[] memory ctx) internal pure returns (uint256[] memory friSteps) { uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { friSteps := mload(friStepsPtr) } } } contract MimcOods is MemoryMap, StarkParameters { // For each query point we want to invert (2 + N_ROWS_IN_MASK) items: // The query point itself (x). // The denominator for the constraint polynomial (x-z^constraintDegree) // [(x-(g^rowNumber)z) for rowNumber in mask]. uint256 constant internal BATCH_INVERSE_CHUNK = (2 + N_ROWS_IN_MASK); uint256 constant internal BATCH_INVERSE_SIZE = MAX_N_QUERIES * BATCH_INVERSE_CHUNK; /* Builds and sums boundary constraints that check that the prover provided the proper evaluations out of domain evaluations for the trace and composition columns. The inputs to this function are: The verifier context. The boundary constraints for the trace enforce claims of the form f(g^k*z) = c by requiring the quotient (f(x) - c)/(x-g^k*z) to be a low degree polynomial. The boundary constraints for the composition enforce claims of the form h(z^d) = c by requiring the quotient (h(x) - c)/(x-z^d) to be a low degree polynomial. Where: f is a trace column. h is a composition column. z is the out of domain sampling point. g is the trace generator k is the offset in the mask. d is the degree of the composition polynomial. c is the evaluation sent by the prover. */ function() external { // This funciton assumes that the calldata contains the context as defined in MemoryMap.sol. // Note that ctx is a variable size array so the first uint256 cell contrains it's length. uint256[] memory ctx; assembly { let ctxSize := mul(add(calldataload(0), 1), 0x20) ctx := mload(0x40) mstore(0x40, add(ctx, ctxSize)) calldatacopy(ctx, 0, ctxSize) } uint256[] memory batchInverseArray = new uint256[](2 * BATCH_INVERSE_SIZE); oodsPrepareInverses(ctx, batchInverseArray); uint256 kMontgomeryRInv_ = PrimeFieldElement6.K_MONTGOMERY_R_INV; assembly { let PRIME := 0x30000003000000010000000000000001 let kMontgomeryRInv := kMontgomeryRInv_ let context := ctx let friQueue := /*friQueue*/ add(context, 0xda0) let friQueueEnd := add(friQueue, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x60)) let traceQueryResponses := /*traceQueryQesponses*/ add(context, 0x3d80) let compositionQueryResponses := /*composition_query_responses*/ add(context, 0xb580) // Set denominatorsPtr to point to the batchInverseOut array. // The content of batchInverseOut is described in oodsPrepareInverses. let denominatorsPtr := add(batchInverseArray, 0x20) for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { // res accumulates numbers modulo PRIME. Since 1814839283484201961915354863390654471405*PRIME < 2**256, we may add up to // 1814839283484201961915354863390654471405 numbers without fear of overflow, and use addmod modulo PRIME only every // 1814839283484201961915354863390654471405 iterations, and once more at the very end. let res := 0 // Trace constraints. // Mask items for column #0. { // Read the next element. let columnValue := mulmod(mload(traceQueryResponses), kMontgomeryRInv, PRIME) // res += c_0*(f_0(x) - f_0(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[0]*/ mload(add(context, 0x3a80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[0]*/ mload(add(context, 0x3180)))), PRIME)) // res += c_1*(f_0(x) - f_0(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[1]*/ mload(add(context, 0x3aa0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[1]*/ mload(add(context, 0x31a0)))), PRIME)) } // Mask items for column #1. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_2*(f_1(x) - f_1(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[2]*/ mload(add(context, 0x3ac0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[2]*/ mload(add(context, 0x31c0)))), PRIME)) } // Mask items for column #2. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x40)), kMontgomeryRInv, PRIME) // res += c_3*(f_2(x) - f_2(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[3]*/ mload(add(context, 0x3ae0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[3]*/ mload(add(context, 0x31e0)))), PRIME)) } // Mask items for column #3. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x60)), kMontgomeryRInv, PRIME) // res += c_4*(f_3(x) - f_3(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[4]*/ mload(add(context, 0x3b00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[4]*/ mload(add(context, 0x3200)))), PRIME)) } // Mask items for column #4. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x80)), kMontgomeryRInv, PRIME) // res += c_5*(f_4(x) - f_4(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[5]*/ mload(add(context, 0x3b20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[5]*/ mload(add(context, 0x3220)))), PRIME)) } // Mask items for column #5. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xa0)), kMontgomeryRInv, PRIME) // res += c_6*(f_5(x) - f_5(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[6]*/ mload(add(context, 0x3b40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[6]*/ mload(add(context, 0x3240)))), PRIME)) } // Mask items for column #6. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xc0)), kMontgomeryRInv, PRIME) // res += c_7*(f_6(x) - f_6(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[7]*/ mload(add(context, 0x3b60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[7]*/ mload(add(context, 0x3260)))), PRIME)) } // Mask items for column #7. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xe0)), kMontgomeryRInv, PRIME) // res += c_8*(f_7(x) - f_7(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[8]*/ mload(add(context, 0x3b80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[8]*/ mload(add(context, 0x3280)))), PRIME)) } // Mask items for column #8. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x100)), kMontgomeryRInv, PRIME) // res += c_9*(f_8(x) - f_8(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[9]*/ mload(add(context, 0x3ba0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[9]*/ mload(add(context, 0x32a0)))), PRIME)) } // Mask items for column #9. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x120)), kMontgomeryRInv, PRIME) // res += c_10*(f_9(x) - f_9(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[10]*/ mload(add(context, 0x3bc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[10]*/ mload(add(context, 0x32c0)))), PRIME)) } // Mask items for column #10. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x140)), kMontgomeryRInv, PRIME) // res += c_11*(f_10(x) - f_10(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[11]*/ mload(add(context, 0x3be0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[11]*/ mload(add(context, 0x32e0)))), PRIME)) // res += c_12*(f_10(x) - f_10(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[12]*/ mload(add(context, 0x3c00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[12]*/ mload(add(context, 0x3300)))), PRIME)) } // Mask items for column #11. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x160)), kMontgomeryRInv, PRIME) // res += c_13*(f_11(x) - f_11(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[13]*/ mload(add(context, 0x3c20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[13]*/ mload(add(context, 0x3320)))), PRIME)) } // Mask items for column #12. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x180)), kMontgomeryRInv, PRIME) // res += c_14*(f_12(x) - f_12(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[14]*/ mload(add(context, 0x3c40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[14]*/ mload(add(context, 0x3340)))), PRIME)) } // Mask items for column #13. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1a0)), kMontgomeryRInv, PRIME) // res += c_15*(f_13(x) - f_13(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[15]*/ mload(add(context, 0x3c60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[15]*/ mload(add(context, 0x3360)))), PRIME)) } // Mask items for column #14. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1c0)), kMontgomeryRInv, PRIME) // res += c_16*(f_14(x) - f_14(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[16]*/ mload(add(context, 0x3c80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[16]*/ mload(add(context, 0x3380)))), PRIME)) } // Mask items for column #15. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1e0)), kMontgomeryRInv, PRIME) // res += c_17*(f_15(x) - f_15(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[17]*/ mload(add(context, 0x3ca0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[17]*/ mload(add(context, 0x33a0)))), PRIME)) } // Mask items for column #16. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x200)), kMontgomeryRInv, PRIME) // res += c_18*(f_16(x) - f_16(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[18]*/ mload(add(context, 0x3cc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[18]*/ mload(add(context, 0x33c0)))), PRIME)) } // Mask items for column #17. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x220)), kMontgomeryRInv, PRIME) // res += c_19*(f_17(x) - f_17(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[19]*/ mload(add(context, 0x3ce0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[19]*/ mload(add(context, 0x33e0)))), PRIME)) } // Mask items for column #18. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x240)), kMontgomeryRInv, PRIME) // res += c_20*(f_18(x) - f_18(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[20]*/ mload(add(context, 0x3d00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[20]*/ mload(add(context, 0x3400)))), PRIME)) } // Mask items for column #19. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x260)), kMontgomeryRInv, PRIME) // res += c_21*(f_19(x) - f_19(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[21]*/ mload(add(context, 0x3d20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[21]*/ mload(add(context, 0x3420)))), PRIME)) } // Advance traceQueryResponses by amount read (0x20 * nTraceColumns). traceQueryResponses := add(traceQueryResponses, 0x280) // Composition constraints. { // Read the next element. let columnValue := mulmod(mload(compositionQueryResponses), kMontgomeryRInv, PRIME) // res += c_22*(h_0(x) - C_0(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[22]*/ mload(add(context, 0x3d40)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[0]*/ mload(add(context, 0x3440)))), PRIME)) } { // Read the next element. let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_23*(h_1(x) - C_1(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[23]*/ mload(add(context, 0x3d60)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[1]*/ mload(add(context, 0x3460)))), PRIME)) } // Advance compositionQueryResponses by amount read (0x20 * constraintDegree). compositionQueryResponses := add(compositionQueryResponses, 0x40) // Append the friValue, which is the sum of the out-of-domain-sampling boundary // constraints for the trace and composition polynomials, to the friQueue array. mstore(add(friQueue, 0x20), mod(res, PRIME)) // Append the friInvPoint of the current query to the friQueue array. mstore(add(friQueue, 0x40), /*friInvPoint*/ mload(add(denominatorsPtr,0x60))) // Advance denominatorsPtr by chunk size (0x20 * (2+N_ROWS_IN_MASK)). denominatorsPtr := add(denominatorsPtr, 0x80) } return(/*friQueue*/ add(context, 0xda0), 0x1200) } } /* Computes and performs batch inverse on all the denominators required for the out of domain sampling boundary constraints. Since the friEvalPoints are calculated during the computation of the denominators this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. */ function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) internal view { uint256 evalCosetOffset_ = PrimeFieldElement6.GENERATOR_VAL; // The array expmodsAndPoints stores subexpressions that are needed // for the denominators computation. // The array is segmented as follows: // expmodsAndPoints[0:0] (.expmods) expmods used during calculations of the points below. // expmodsAndPoints[0:2] (.points) points used during the denominators calculation. uint256[2] memory expmodsAndPoints; assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40)) let PRIME := 0x30000003000000010000000000000001 // Prepare expmods for computations of trace generator powers. let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60)) { // point = -z. let point := sub(PRIME, oodsPoint) // Compute denominators for rows with nonconst mask expression. // We compute those first because for the const rows we modify the point variable. // Compute denominators for rows with const mask expression. // expmods_and_points.points[0] = -z. mstore(add(expmodsAndPoints, 0x0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[1] = -(g * z). mstore(add(expmodsAndPoints, 0x20), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) for {} lt(evalPointsPtr, evalPointsEndPtr) {evalPointsPtr := add(evalPointsPtr, 0x20)} { let evalPoint := mload(evalPointsPtr) // Shift evalPoint to evaluation domain coset. let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { // Calculate denominator for row 0: x - z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 1: x - g * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate the denominator for the composition polynomial columns: x - z^2. let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } // Add evalPoint to batch inverse inputs. // inverse(evalPoint) is going to be used by FRI. mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) // Advance pointers. productsPtr := add(productsPtr, 0x80) valuesPtr := add(valuesPtr, 0x80) } let productsToValuesOffset := 0x1800 let firstPartialProductPtr := add(batchInverseArray, 0x20) // Compute the inverse of the product. let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := productsPtr // Loop in blocks of size 8 as much as possible: we can loop over a full block as long as // currentPartialProductPtr >= firstPartialProductPtr + 8*0x20, or equivalently, // currentPartialProductPtr > firstPartialProductPtr + 7*0x20. // We use the latter comparison since there is no >= evm opcode. let midPartialProductPtr := add(firstPartialProductPtr, 0xe0) for { } gt(currentPartialProductPtr, midPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } // Loop over the remainder. for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } } } contract Fri is MemoryMap, MemoryAccessUtils, HornerEvaluator, FriLayer { event LogGas(string name, uint256 val); function verifyLastLayer(uint256[] memory ctx, uint256 nPoints) internal { uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1; uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR]; for (uint256 i = 0; i < nPoints; i++) { uint256 point = ctx[MM_FRI_QUEUE + 3*i + 2]; // Invert point using inverse(point) == fpow(point, ord(point) - 1). point = fpow(point, groupOrderMinusOne); require( hornerEval(coefsStart, point, friLastLayerDegBound) == ctx[MM_FRI_QUEUE + 3*i + 1], "Bad Last layer value."); } } /* Verifies FRI layers. Upon entry and every time we pass through the "if (index < layerSize)" condition, ctx[mmFriQueue:] holds an array of triplets (query index, FRI value, FRI inversed point), i.e. ctx[mmFriQueue::3] holds query indices. ctx[mmFriQueue + 1::3] holds the input for the next layer. ctx[mmFriQueue + 2::3] holds the inverses of the evaluation points: ctx[mmFriQueue + 3*i + 2] = inverse( fpow(layerGenerator, bitReverse(ctx[mmFriQueue + 3*i], logLayerSize)). */ function friVerifyLayers( uint256[] memory ctx) internal { uint256 friCtx = getPtr(ctx, MM_FRI_CTX); require( MAX_SUPPORTED_MAX_FRI_STEP == FRI_MAX_FRI_STEP, "Incosistent MAX_FRI_STEP between MemoryMap.sol and FriLayer.sol"); initFriGroups(friCtx); // emit LogGas("FRI offset precomputation", gasleft()); uint256 channelPtr = getChannelPtr(ctx); uint256 merkleQueuePtr = getMerkleQueuePtr(ctx); uint256 friStep = 1; uint256 nLiveQueries = ctx[MM_N_UNIQUE_QUERIES]; // Add 0 at the end of the queries array to avoid empty array check in readNextElment. ctx[MM_FRI_QUERIES_DELIMITER] = 0; // Rather than converting all the values from Montgomery to standard form, // we can just pretend that the values are in standard form but all // the committed polynomials are multiplied by MontgomeryR. // // The values in the proof are already multiplied by MontgomeryR, // but the inputs from the OODS oracle need to be fixed. for (uint256 i = 0; i < nLiveQueries; i++ ) { ctx[MM_FRI_QUEUE + 3*i + 1] = fmul(ctx[MM_FRI_QUEUE + 3*i + 1], K_MONTGOMERY_R); } uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256[] memory friSteps = getFriSteps(ctx); uint256 nFriSteps = friSteps.length; while (friStep < nFriSteps) { uint256 friCosetSize = 2**friSteps[friStep]; nLiveQueries = computeNextLayer( channelPtr, friQueue, merkleQueuePtr, nLiveQueries, ctx[MM_FRI_EVAL_POINTS + friStep], friCosetSize, friCtx); // emit LogGas( // string(abi.encodePacked("FRI layer ", bytes1(uint8(48 + friStep)))), gasleft()); // Layer is done, verify the current layer and move to next layer. // ctx[mmMerkleQueue: merkleQueueIdx) holds the indices // and values of the merkle leaves that need verification. verify( channelPtr, merkleQueuePtr, bytes32(ctx[MM_FRI_COMMITMENTS + friStep - 1]), nLiveQueries); // emit LogGas( // string(abi.encodePacked("Merkle of FRI layer ", bytes1(uint8(48 + friStep)))), // gasleft()); friStep++; } verifyLastLayer(ctx, nLiveQueries); // emit LogGas("last FRI layer", gasleft()); } } contract StarkVerifier is MemoryMap, MemoryAccessUtils, VerifierChannel, IStarkVerifier, Fri { /* The work required to generate an invalid proof is 2^numSecurityBits. Typical values: 80-128. */ uint256 numSecurityBits; /* The secuirty of a proof is a composition of bits obtained by PoW and bits obtained by FRI queries. The verifier requires at least minProofOfWorkBits to be obtained by PoW. Typical values: 20-30. */ uint256 minProofOfWorkBits; constructor(uint256 numSecurityBits_, uint256 minProofOfWorkBits_) public { numSecurityBits = numSecurityBits_; minProofOfWorkBits = minProofOfWorkBits_; } /* To print LogDebug messages from assembly use code like the following: assembly { let val := 0x1234 mstore(0, val) // uint256 val // log to the LogDebug(uint256) topic log1(0, 0x20, 0x2feb477e5c8c82cfb95c787ed434e820b1a28fa84d68bbf5aba5367382f5581c) } Note that you can't use log in a contract that was called with staticcall (ContraintPoly, Oods,...) If logging is needed replace the staticcall to call and add a third argument of 0. */ event LogBool(bool val); event LogDebug(uint256 val); address oodsContractAddress; function airSpecificInit(uint256[] memory publicInput) internal returns (uint256[] memory ctx, uint256 logTraceLength); uint256 constant internal PROOF_PARAMS_N_QUERIES_OFFSET = 0; uint256 constant internal PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET = 1; uint256 constant internal PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET = 2; uint256 constant internal PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET = 3; uint256 constant internal PROOF_PARAMS_N_FRI_STEPS_OFFSET = 4; uint256 constant internal PROOF_PARAMS_FRI_STEPS_OFFSET = 5; function validateFriParams( uint256[] memory friSteps, uint256 logTraceLength, uint256 logFriLastLayerDegBound) internal pure { require (friSteps[0] == 0, "Only eta0 == 0 is currently supported"); uint256 expectedLogDegBound = logFriLastLayerDegBound; uint256 nFriSteps = friSteps.length; for (uint256 i = 1; i < nFriSteps; i++) { uint256 friStep = friSteps[i]; require(friStep > 0, "Only the first fri step can be 0"); require(friStep <= 4, "Max supported fri step is 4."); expectedLogDegBound += friStep; } // FRI starts with a polynomial of degree 'traceLength'. // After applying all the FRI steps we expect to get a polynomial of degree less // than friLastLayerDegBound. require ( expectedLogDegBound == logTraceLength, "Fri params do not match trace length"); } function initVerifierParams(uint256[] memory publicInput, uint256[] memory proofParams) internal returns (uint256[] memory ctx) { require (proofParams.length > PROOF_PARAMS_FRI_STEPS_OFFSET, "Invalid proofParams."); require ( proofParams.length == ( PROOF_PARAMS_FRI_STEPS_OFFSET + proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]), "Invalid proofParams."); uint256 logBlowupFactor = proofParams[PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET]; require (logBlowupFactor <= 16, "logBlowupFactor must be at most 16"); require (logBlowupFactor >= 1, "logBlowupFactor must be at least 1"); uint256 proofOfWorkBits = proofParams[PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET]; require (proofOfWorkBits <= 50, "proofOfWorkBits must be at most 50"); require (proofOfWorkBits >= minProofOfWorkBits, "minimum proofOfWorkBits not satisfied"); require (proofOfWorkBits < numSecurityBits, "Proofs may not be purely based on PoW."); uint256 logFriLastLayerDegBound = ( proofParams[PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET] ); require ( logFriLastLayerDegBound <= 10, "logFriLastLayerDegBound must be at most 10."); uint256 nFriSteps = proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]; require (nFriSteps <= 10, "Too many fri steps."); require (nFriSteps > 1, "Not enough fri steps."); uint256[] memory friSteps = new uint256[](nFriSteps); for (uint256 i = 0; i < nFriSteps; i++) { friSteps[i] = proofParams[PROOF_PARAMS_FRI_STEPS_OFFSET + i]; } uint256 logTraceLength; (ctx, logTraceLength) = airSpecificInit(publicInput); validateFriParams(friSteps, logTraceLength, logFriLastLayerDegBound); uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { mstore(friStepsPtr, friSteps) } ctx[MM_FRI_LAST_LAYER_DEG_BOUND] = 2**logFriLastLayerDegBound; ctx[MM_TRACE_LENGTH] = 2 ** logTraceLength; ctx[MM_BLOW_UP_FACTOR] = 2**logBlowupFactor; ctx[MM_PROOF_OF_WORK_BITS] = proofOfWorkBits; uint256 nQueries = proofParams[PROOF_PARAMS_N_QUERIES_OFFSET]; require (nQueries > 0, "Number of queries must be at least one"); require (nQueries <= MAX_N_QUERIES, "Too many queries."); require ( nQueries * logBlowupFactor + proofOfWorkBits >= numSecurityBits, "Proof params do not satisfy security requirements."); ctx[MM_N_UNIQUE_QUERIES] = nQueries; // We start with log_evalDomainSize = logTraceSize and update it here. ctx[MM_LOG_EVAL_DOMAIN_SIZE] = logTraceLength + logBlowupFactor; ctx[MM_EVAL_DOMAIN_SIZE] = 2**ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 gen_evalDomain = fpow(GENERATOR_VAL, (K_MODULUS - 1) / ctx[MM_EVAL_DOMAIN_SIZE]); ctx[MM_EVAL_DOMAIN_GENERATOR] = gen_evalDomain; uint256 genTraceDomain = fpow(gen_evalDomain, ctx[MM_BLOW_UP_FACTOR]); ctx[MM_TRACE_GENERATOR] = genTraceDomain; } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32); function oodsConsistencyCheck(uint256[] memory ctx) internal; function getNColumnsInTrace() internal pure returns(uint256); function getNColumnsInComposition() internal pure returns(uint256); function getMmCoefficients() internal pure returns(uint256); function getMmOodsValues() internal pure returns(uint256); function getMmOodsCoefficients() internal pure returns(uint256); function getNCoefficients() internal pure returns(uint256); function getNOodsValues() internal pure returns(uint256); function getNOodsCoefficients() internal pure returns(uint256); function hashRow(uint256[] memory ctx, uint256 offset, uint256 length) internal pure returns (uint256 res) { assembly { res := keccak256(add(add(ctx, 0x20), offset), length) } res &= getHashMask(); } /* Adjusts the query indices and generates evaluation points for each query index. The operations above are independent but we can save gas by combining them as both operations require us to iterate the queries array. Indices adjustment: The query indices adjustment is needed because both the Merkle verification and FRI expect queries "full binary tree in array" indices. The adjustment is simply adding evalDomainSize to each query. Note that evalDomainSize == 2^(#FRI layers) == 2^(Merkle tree hight). evalPoints generation: for each query index "idx" we compute the corresponding evaluation point: g^(bitReverse(idx, log_evalDomainSize). */ function adjustQueryIndicesAndPrepareEvalPoints(uint256[] memory ctx) internal { uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 evalPointsPtr = getPtr(ctx, MM_OODS_EVAL_POINTS); uint256 log_evalDomainSize = ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 evalDomainSize = ctx[MM_EVAL_DOMAIN_SIZE]; uint256 evalDomainGenerator = ctx[MM_EVAL_DOMAIN_GENERATOR]; assembly { /* Returns the bit reversal of value assuming it has the given number of bits. numberOfBits must be <= 64. */ function bitReverse(value, numberOfBits) -> res { // Bit reverse value by swapping 1 bit chunks then 2 bit chunks and so forth. // Each swap is done by masking out and shifting one of the chunks by twice its size. // Finally, we use div to align the result to the right. res := value // Swap 1 bit chunks. res := or(mul(and(res, 0x5555555555555555), 0x4), and(res, 0xaaaaaaaaaaaaaaaa)) // Swap 2 bit chunks. res := or(mul(and(res, 0x6666666666666666), 0x10), and(res, 0x19999999999999998)) // Swap 4 bit chunks. res := or(mul(and(res, 0x7878787878787878), 0x100), and(res, 0x78787878787878780)) // Swap 8 bit chunks. res := or(mul(and(res, 0x7f807f807f807f80), 0x10000), and(res, 0x7f807f807f807f8000)) // Swap 16 bit chunks. res := or(mul(and(res, 0x7fff80007fff8000), 0x100000000), and(res, 0x7fff80007fff80000000)) // Swap 32 bit chunks. res := or(mul(and(res, 0x7fffffff80000000), 0x10000000000000000), and(res, 0x7fffffff8000000000000000)) // Right align the result. res := div(res, exp(2, sub(127, numberOfBits))) } function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let PRIME := 0x30000003000000010000000000000001 for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let queryIdx := mload(friQueue) // Adjust queryIdx, see comment in function description. let adjustedQueryIdx := add(queryIdx, evalDomainSize) mstore(friQueue, adjustedQueryIdx) // Compute the evaluation point corresponding to the current queryIdx. mstore(evalPointsPtr, expmod(evalDomainGenerator, bitReverse(queryIdx, log_evalDomainSize), PRIME)) evalPointsPtr := add(evalPointsPtr, 0x20) } } } function readQueryResponsesAndDecommit( uint256[] memory ctx, uint256 nColumns, uint256 proofDataPtr, bytes32 merkleRoot) internal view { require(nColumns <= getNColumnsInTrace() + getNColumnsInComposition(), "Too many columns."); uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 channelPtr = getPtr(ctx, MM_CHANNEL); uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 merkleQueuePtr = getPtr(ctx, MM_MERKLE_QUEUE); uint256 rowSize = 0x20 * nColumns; uint256 lhashMask = getHashMask(); assembly { let proofPtr := mload(channelPtr) let merklePtr := merkleQueuePtr for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let merkleLeaf := and(keccak256(proofPtr, rowSize), lhashMask) if eq(rowSize, 0x20) { // If a leaf contains only 1 field element we don't hash it. merkleLeaf := mload(proofPtr) } // push(queryIdx, hash(row)) to merkleQueue. mstore(merklePtr, mload(friQueue)) mstore(add(merklePtr, 0x20), merkleLeaf) merklePtr := add(merklePtr, 0x40) // Copy query responses to proofData array. // This array will be sent to the OODS contract. for {let proofDataChunk_end := add(proofPtr, rowSize)} lt(proofPtr, proofDataChunk_end) {proofPtr := add(proofPtr, 0x20)} { mstore(proofDataPtr, mload(proofPtr)) proofDataPtr := add(proofDataPtr, 0x20) } } mstore(channelPtr, proofPtr) } verify(channelPtr, merkleQueuePtr, merkleRoot, nUniqueQueries); } /* Computes the first FRI layer by reading the query responses and calling the OODS contract. The OODS contract will build and sum boundary constraints that check that the prover provided the proper evaluations for the Out of Domain Sampling. I.e. if the prover said that f(z) = c, the first FRI layer will include the term (f(x) - c)/(x-z). */ function computeFirstFriLayer(uint256[] memory ctx) internal { adjustQueryIndicesAndPrepareEvalPoints(ctx); // emit LogGas("Prepare evaluation points", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInTrace(), getPtr(ctx, MM_TRACE_QUERY_RESPONSES), bytes32(ctx[MM_TRACE_COMMITMENT])); // emit LogGas("Read and decommit trace", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInComposition(), getPtr(ctx, MM_COMPOSITION_QUERY_RESPONSES), bytes32(ctx[MM_OODS_COMMITMENT])); // emit LogGas("Read and decommit composition", gasleft()); address oodsAddress = oodsContractAddress; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 returnDataSize = MAX_N_QUERIES * 0x60; assembly { // Call the OODS contract. if iszero(staticcall(not(0), oodsAddress, ctx, /*sizeof(ctx)*/ mul(add(mload(ctx), 1), 0x20), friQueue, returnDataSize)) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // emit LogGas("OODS virtual oracle", gasleft()); } /* Reads the last FRI layer (i.e. the polynomial's coefficients) from the channel. This differs from standard reading of channel field elements in several ways: -- The digest is updated by hashing it once with all coefficients simultaneously, rather than iteratively one by one. -- The coefficients are kept in Montgomery form, as is the case throughout the FRI computation. -- The coefficients are not actually read and copied elsewhere, but rather only a pointer to their location in the channel is stored. */ function readLastFriLayer(uint256[] memory ctx) internal pure { uint256 lmmChannel = MM_CHANNEL; uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 lastLayerPtr; uint256 badInput = 0; assembly { let primeMinusOne := 0x30000003000000010000000000000000 let channelPtr := add(add(ctx, 0x20), mul(lmmChannel, 0x20)) lastLayerPtr := mload(channelPtr) // Make sure all the values are valid field elements. let length := mul(friLastLayerDegBound, 0x20) let lastLayerEnd := add(lastLayerPtr, length) for { let coefsPtr := lastLayerPtr } lt(coefsPtr, lastLayerEnd) { coefsPtr := add(coefsPtr, 0x20) } { badInput := or(badInput, gt(mload(coefsPtr), primeMinusOne)) } // Copy the digest to the proof area // (store it before the coefficients - this is done because // keccak256 needs all data to be consecutive), // then hash and place back in digestPtr. let newDigestPtr := sub(lastLayerPtr, 0x20) let digestPtr := add(channelPtr, 0x20) // Overwriting the proof to minimize copying of data. mstore(newDigestPtr, mload(digestPtr)) // prng.digest := keccak256(digest||lastLayerCoefs). mstore(digestPtr, keccak256(newDigestPtr, add(length, 0x20))) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) // Note: proof pointer is not incremented until this point. mstore(channelPtr, lastLayerEnd) } require(badInput == 0, "Invalid field element."); ctx[MM_FRI_LAST_LAYER_PTR] = lastLayerPtr; } function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput) internal { // emit LogGas("Transmission", gasleft()); uint256[] memory ctx = initVerifierParams(publicInput, proofParams); uint256 channelPtr = getChannelPtr(ctx); initChannel(channelPtr, getProofPtr(proof), getPublicInputHash(publicInput)); // emit LogGas("Initializations", gasleft()); // Read trace commitment. ctx[MM_TRACE_COMMITMENT] = uint256(readHash(channelPtr, true)); VerifierChannel.sendFieldElements( channelPtr, getNCoefficients(), getPtr(ctx, getMmCoefficients())); // emit LogGas("Generate coefficients", gasleft()); ctx[MM_OODS_COMMITMENT] = uint256(readHash(channelPtr, true)); // Send Out of Domain Sampling point. VerifierChannel.sendFieldElements(channelPtr, 1, getPtr(ctx, MM_OODS_POINT)); // Read the answers to the Out of Domain Sampling. uint256 lmmOodsValues = getMmOodsValues(); for (uint256 i = lmmOodsValues; i < lmmOodsValues+getNOodsValues(); i++) { ctx[i] = VerifierChannel.readFieldElement(channelPtr, true); } // emit LogGas("Read OODS commitments", gasleft()); oodsConsistencyCheck(ctx); // emit LogGas("OODS consistency check", gasleft()); VerifierChannel.sendFieldElements( channelPtr, getNOodsCoefficients(), getPtr(ctx, getMmOodsCoefficients())); // emit LogGas("Generate OODS coefficients", gasleft()); ctx[MM_FRI_COMMITMENTS] = uint256(VerifierChannel.readHash(channelPtr, true)); uint256 nFriSteps = getFriSteps(ctx).length; uint256 fri_evalPointPtr = getPtr(ctx, MM_FRI_EVAL_POINTS); for (uint256 i = 1; i < nFriSteps - 1; i++) { VerifierChannel.sendFieldElements(channelPtr, 1, fri_evalPointPtr + i * 0x20); ctx[MM_FRI_COMMITMENTS + i] = uint256(VerifierChannel.readHash(channelPtr, true)); } // Send last random FRI evaluation point. VerifierChannel.sendFieldElements( channelPtr, 1, getPtr(ctx, MM_FRI_EVAL_POINTS + nFriSteps - 1)); // Read FRI last layer commitment. readLastFriLayer(ctx); // Generate queries. // emit LogGas("Read FRI commitments", gasleft()); VerifierChannel.verifyProofOfWork(channelPtr, ctx[MM_PROOF_OF_WORK_BITS]); ctx[MM_N_UNIQUE_QUERIES] = VerifierChannel.sendRandomQueries( channelPtr, ctx[MM_N_UNIQUE_QUERIES], ctx[MM_EVAL_DOMAIN_SIZE] - 1, getPtr(ctx, MM_FRI_QUEUE), 0x60); // emit LogGas("Send queries", gasleft()); computeFirstFriLayer(ctx); friVerifyLayers(ctx); } } contract MimcVerifier is StarkParameters, StarkVerifier, FactRegistry, PublicInputOffsets{ MimcConstraintPoly constraintPoly; PeriodicColumnContract[20] constantsCols; uint256 internal constant PUBLIC_INPUT_SIZE = 5; constructor( address[] memory auxPolynomials, MimcOods oodsContract, uint256 numSecurityBits_, uint256 minProofOfWorkBits_) StarkVerifier( numSecurityBits_, minProofOfWorkBits_ ) public { constraintPoly = MimcConstraintPoly(auxPolynomials[0]); for (uint256 i = 0; i < 20; i++) { constantsCols[i] = PeriodicColumnContract(auxPolynomials[i+1]); } oodsContractAddress = address(oodsContract); } function verifyProofAndRegister( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata publicInput ) external { verifyProof(proofParams, proof, publicInput); registerFact( keccak256( abi.encodePacked( 10 * 2**publicInput[OFFSET_LOG_TRACE_LENGTH] - 1, publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y] ) ) ); } function getNColumnsInTrace() internal pure returns (uint256) { return N_COLUMNS_IN_MASK; } function getNColumnsInComposition() internal pure returns (uint256) { return CONSTRAINTS_DEGREE_BOUND; } function getMmCoefficients() internal pure returns (uint256) { return MM_COEFFICIENTS; } function getMmOodsValues() internal pure returns (uint256) { return MM_OODS_VALUES; } function getMmOodsCoefficients() internal pure returns (uint256) { return MM_OODS_COEFFICIENTS; } function getNCoefficients() internal pure returns (uint256) { return N_COEFFICIENTS; } function getNOodsValues() internal pure returns (uint256) { return N_OODS_VALUES; } function getNOodsCoefficients() internal pure returns (uint256) { return N_OODS_COEFFICIENTS; } function airSpecificInit(uint256[] memory publicInput) internal returns (uint256[] memory ctx, uint256 logTraceLength) { require(publicInput.length == PUBLIC_INPUT_SIZE, "INVALID_PUBLIC_INPUT_LENGTH" ); ctx = new uint256[](MM_CONTEXT_SIZE); // Note that the prover does the VDF computation the other way around (uses the inverse // function), hence vdf_output is the input for its calculation, and vdf_input should be the // result of the calculation. ctx[MM_INPUT_VALUE_A] = publicInput[OFFSET_VDF_OUTPUT_X]; ctx[MM_INPUT_VALUE_B] = publicInput[OFFSET_VDF_OUTPUT_Y]; ctx[MM_OUTPUT_VALUE_A] = publicInput[OFFSET_VDF_INPUT_X]; ctx[MM_OUTPUT_VALUE_B] = publicInput[OFFSET_VDF_INPUT_Y]; // Initialize the MDS matrix values with fixed predefined values. ctx[MM_MAT00] = 0x109bbc181e07a285856e0d8bde02619; ctx[MM_MAT01] = 0x1eb8859b1b789cd8a80927a32fdf41f7; ctx[MM_MAT10] = 0xdc8eaac802c8f9cb9dff6ed0728012d; ctx[MM_MAT11] = 0x2c18506f35eab63b58143a34181c89e; logTraceLength = publicInput[OFFSET_LOG_TRACE_LENGTH]; require(logTraceLength <= 50, "logTraceLength must not exceed 50."); } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32) { return keccak256( abi.encodePacked( uint64(2 ** publicInput[OFFSET_LOG_TRACE_LENGTH]), publicInput[OFFSET_VDF_OUTPUT_X], publicInput[OFFSET_VDF_OUTPUT_Y], publicInput[OFFSET_VDF_INPUT_X], publicInput[OFFSET_VDF_INPUT_Y]) ); } /* Checks that the trace and the composition agree on the Out of Domain Sampling point, assuming the prover provided us with the proper evaluations. Later, we use boundary constraints to check that those evaluations are actually consistent with the committed trace and composition polynomials. */ function oodsConsistencyCheck(uint256[] memory ctx) internal { uint256 oodsPoint = ctx[MM_OODS_POINT]; uint256 nRows = 256; uint256 zPointPow = fpow(oodsPoint, ctx[MM_TRACE_LENGTH] / nRows); ctx[MM_PERIODIC_COLUMN__CONSTS0_A] = constantsCols[0].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_A] = constantsCols[1].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_A] = constantsCols[2].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_A] = constantsCols[3].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_A] = constantsCols[4].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_A] = constantsCols[5].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_A] = constantsCols[6].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_A] = constantsCols[7].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_A] = constantsCols[8].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_A] = constantsCols[9].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS0_B] = constantsCols[10].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS1_B] = constantsCols[11].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS2_B] = constantsCols[12].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS3_B] = constantsCols[13].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS4_B] = constantsCols[14].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS5_B] = constantsCols[15].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS6_B] = constantsCols[16].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS7_B] = constantsCols[17].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS8_B] = constantsCols[18].compute(zPointPow); ctx[MM_PERIODIC_COLUMN__CONSTS9_B] = constantsCols[19].compute(zPointPow); uint256 compositionFromTraceValue; address lconstraintPoly = address(constraintPoly); uint256 offset = 0x20 * (1 + MM_CONSTRAINT_POLY_ARGS_START); uint256 size = 0x20 * (MM_CONSTRAINT_POLY_ARGS_END - MM_CONSTRAINT_POLY_ARGS_START); assembly { // Call MimcConstraintPoly contract. let p := mload(0x40) if iszero(staticcall(not(0), lconstraintPoly, add(ctx, offset), size, p, 0x20)) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } compositionFromTraceValue := mload(p) } uint256 claimedComposition = fadd( ctx[MM_OODS_VALUES + MASK_SIZE], fmul(oodsPoint, ctx[MM_OODS_VALUES + MASK_SIZE + 1])); require( compositionFromTraceValue == claimedComposition, "claimedComposition does not match trace"); } }
uint256 res = fmul(val, kMontgomeryRInv);
function fromMontgomery(uint256 val) internal pure returns (uint256 res) { assembly { res := mulmod( val, 0x9000001200000096000000600000001, 0x30000003000000010000000000000001 ) } return res; }
7,337,991
[ 1, 11890, 5034, 400, 273, 10940, 332, 12, 1125, 16, 417, 49, 1580, 75, 362, 627, 54, 3605, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 628, 49, 1580, 75, 362, 627, 12, 11890, 5034, 1244, 13, 2713, 16618, 1135, 261, 11890, 5034, 400, 13, 288, 203, 203, 203, 3639, 19931, 288, 203, 203, 5411, 400, 519, 14064, 1711, 12, 203, 203, 7734, 1244, 16, 203, 203, 7734, 374, 92, 29, 2787, 1611, 22, 9449, 10525, 9449, 26, 9449, 1611, 16, 203, 203, 7734, 374, 92, 23, 9449, 23, 9449, 1611, 12648, 9449, 1611, 203, 203, 5411, 262, 203, 203, 3639, 289, 203, 203, 3639, 327, 400, 31, 203, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 ProjectContract { address constant public receiver = 0x4FE35e4051D5Ba164eD2738B6ebC7083A4953B62; uint constant public total = 50 ether; uint constant public interest = 5; uint public fundingEnd; enum State { Init, Running, Funded, Failed, Redemption, Closed } State public state = State.Init; mapping(address => uint) public investments; mapping(address => uint) public interests; address[] public investors; // event InvestedAmountIncreased(uint amount); // event FundingStarted(); // event FundingSuccessful(); // event FundingFailed(); // event FundingClosed(); // event InvestmentWithInterestClaimed(address receiver, uint amount); // event FundedAmountTransfered(address receiver, uint amount); modifier verifyAmount() { require(address(this).balance <= total); _; } modifier initPhase() { require(state == State.Init); _; } modifier fundingPhase() { require(state == State.Running && now < fundingEnd); _; } modifier redemptionPhase() { require(state == State.Redemption); _; } modifier closedPhase() { require(state == State.Closed); _; } function startFunding() external initPhase { state = State.Running; fundingEnd = now + 1 days; // emit FundingStarted(); } function getCurrentFundingBalance() external view returns(uint) { return address(this).balance; } function invest() external payable verifyAmount fundingPhase { // emit InvestedAmountIncreased(address(this).balance); investments[msg.sender] += msg.value; interests[msg.sender] += (msg.value / 100 * interest); bool alreadyInvestor = false; for (uint i = 0; i < investors.length; i++) { if (investors[i] == msg.sender) { alreadyInvestor = true; break; } } if (!alreadyInvestor) { investors.push(msg.sender); } if (address(this).balance == total) { state = State.Funded; // emit FundingSuccessful(); } } function transferFunds() external { require(now >= fundingEnd || state == State.Funded); require(total == address(this).balance); receiver.transfer(address(this).balance); // emit FundedAmountTransfered(receiver, address(this).balance); state = State.Redemption; } function payInterest() external payable { require(msg.sender == receiver); require(msg.value == (total / 100 * interest)); } function payLoan() external payable { require(msg.sender == receiver); require(msg.value == total); } function transferInvestedAmountWithInterest() external redemptionPhase { require(address(this).balance == total + (total / 100 * interest)); for (uint i = 0; i < investors.length; i++) { uint interestAmount = interests[investors[i]]; uint investmentAmount = investments[investors[i]]; if (!investors[i].send(interestAmount + investmentAmount)) { interests[investors[i]] = interestAmount; investments[investors[i]] = investmentAmount; } else { investments[investors[i]] = 0; interests[investors[i]] = 0; // emit InvestmentWithInterestClaimed(msg.sender, amount); } } bool interestPayedBack = true; for (uint j = 0; j < investors.length; j++) { if (interests[investors[j]] != 0) { interestPayedBack = false; break; } } if (interestPayedBack) { // emit FundingClosed(); state = State.Closed; } } function getInvestorCount() external constant returns(uint count) { return investors.length; } }
emit InvestmentWithInterestClaimed(msg.sender, amount); emit FundingClosed();
function transferInvestedAmountWithInterest() external redemptionPhase { require(address(this).balance == total + (total / 100 * interest)); for (uint i = 0; i < investors.length; i++) { uint interestAmount = interests[investors[i]]; uint investmentAmount = investments[investors[i]]; if (!investors[i].send(interestAmount + investmentAmount)) { interests[investors[i]] = interestAmount; investments[investors[i]] = investmentAmount; investments[investors[i]] = 0; interests[investors[i]] = 0; } } bool interestPayedBack = true; for (uint j = 0; j < investors.length; j++) { if (interests[investors[j]] != 0) { interestPayedBack = false; break; } } if (interestPayedBack) { state = State.Closed; } }
7,321,149
[ 1, 18356, 5454, 395, 475, 1190, 29281, 9762, 329, 12, 3576, 18, 15330, 16, 3844, 1769, 3626, 478, 14351, 7395, 5621, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 7412, 3605, 3149, 6275, 1190, 29281, 1435, 3903, 283, 19117, 375, 11406, 288, 203, 203, 565, 2583, 12, 2867, 12, 2211, 2934, 12296, 422, 2078, 397, 261, 4963, 342, 2130, 380, 16513, 10019, 203, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2198, 395, 1383, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2254, 16513, 6275, 273, 16513, 87, 63, 5768, 395, 1383, 63, 77, 13563, 31, 203, 1377, 2254, 2198, 395, 475, 6275, 273, 2198, 395, 1346, 63, 5768, 395, 1383, 63, 77, 13563, 31, 203, 203, 1377, 309, 16051, 5768, 395, 1383, 63, 77, 8009, 4661, 12, 2761, 395, 6275, 397, 2198, 395, 475, 6275, 3719, 288, 203, 3639, 16513, 87, 63, 5768, 395, 1383, 63, 77, 13563, 273, 16513, 6275, 31, 203, 3639, 2198, 395, 1346, 63, 5768, 395, 1383, 63, 77, 13563, 273, 2198, 395, 475, 6275, 31, 203, 3639, 2198, 395, 1346, 63, 5768, 395, 1383, 63, 77, 13563, 273, 374, 31, 203, 3639, 16513, 87, 63, 5768, 395, 1383, 63, 77, 13563, 273, 374, 31, 203, 1377, 289, 203, 565, 289, 203, 203, 565, 1426, 16513, 9148, 329, 2711, 273, 638, 31, 203, 565, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 2198, 395, 1383, 18, 2469, 31, 525, 27245, 288, 203, 1377, 309, 261, 2761, 25563, 63, 5768, 395, 1383, 63, 78, 13563, 480, 374, 13, 288, 203, 3639, 16513, 9148, 329, 2711, 273, 629, 31, 203, 3639, 898, 31, 203, 1377, 289, 203, 565, 289, 203, 203, 565, 309, 261, 2 ]
/** *Submitted for verification at Etherscan.io on 2019-07-11 */ pragma solidity ^0.4.25; contract ERC20 { // function totalSupply() public constant returns (uint supply); // function balanceOf(address who) public constant returns (uint value); // function allowance(address owner, address spender) public constant returns (uint _allowance); function transfer(address to, uint value) public returns (bool success); function transferFrom(address from, address to, uint value) public returns (bool success); function approve(address spender, uint value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * Math operations with safety checks */ contract SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { assert(b > 0); return a / b; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function min(uint x, uint y) internal pure returns (uint) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint) { return x >= y ? x : y; } } contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract Token is ERC20, SafeMath, Owned { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint public totalSupply; // This creates an array with all balances mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; mapping(address=>uint) public lock; mapping(address=>bool) public freezeIn; mapping(address=>bool) public freezeOut; //event definitions /* This notifies clients about the amount burn */ event Burn(address indexed from, uint value); event FreezeIn(address[] indexed from, bool value); event FreezeOut(address[] indexed from, bool value); function Token(string tokenName, string tokenSymbol, uint initSupply) public { totalSupply=initSupply*10**uint(decimals); //update total supply name=tokenName; symbol=tokenSymbol; balanceOf[owner]=totalSupply; //give the owner all initial tokens } //ERC 20 /////////////////////////////////////////////////////////////////////////////////////////// function internalTransfer(address from, address toaddr, uint value) internal { require(toaddr!=0); require(balanceOf[from]>=value); require(now>=lock[from]); require(!freezeIn[toaddr]); require(!freezeOut[from]); balanceOf[from]=sub(balanceOf[from], value); balanceOf[toaddr]=add(balanceOf[toaddr], value); Transfer(from, toaddr, value); } function transfer(address toaddr, uint value) public returns (bool) { internalTransfer(msg.sender, toaddr, value); return true; } function transferFrom(address from, address toaddr, uint value) public returns (bool) { require(allowance[from][msg.sender]>=value); allowance[from][msg.sender]=sub(allowance[from][msg.sender], value); internalTransfer(from, toaddr, value); return true; } function approve(address spender, uint amount) public returns (bool) { require((amount == 0) || (allowance[msg.sender][spender] == 0)); allowance[msg.sender][spender]=amount; Approval(msg.sender, spender, amount); return true; } ///////////////////////////////////////////////////////////////////////////////////////// function setNameSymbol(string tokenName, string tokenSymbol) public onlyOwner { name=tokenName; symbol=tokenSymbol; } //////////////////////////////////////////////////////////////////////////////////////////// function setLock(address[] addrs, uint[] times) public onlyOwner { require(addrs.length==times.length); for (uint i=0; i<addrs.length; i++) { lock[addrs[i]]=times[i]; } } function setFreezeIn(address[] addrs, bool value) public onlyOwner { for (uint i=0; i<addrs.length; i++) { freezeIn[addrs[i]]=value; } FreezeIn(addrs, value); } function setFreezeOut(address[] addrs, bool value) public onlyOwner { for (uint i=0; i<addrs.length; i++) { freezeOut[addrs[i]]=value; } FreezeOut(addrs, value); } /////////////////////////////////////////////////////////////////////////////////////////// function mint(uint amount) public onlyOwner { balanceOf[owner]=add(balanceOf[owner], amount*10**uint(decimals)); totalSupply=add(totalSupply, amount*10**uint(decimals)); } function burn(uint amount) public { balanceOf[msg.sender]=sub(balanceOf[msg.sender], amount*10**uint(decimals)); totalSupply=sub(totalSupply, amount*10**uint(decimals)); } /////////////////////////////////////////////////////////////////////////////////////////// function withdrawEther(uint amount) public onlyOwner { owner.transfer(amount); } // can accept ether function() public payable { } }
This notifies clients about the amount burn */
function Token(string tokenName, string tokenSymbol, uint initSupply) public { name=tokenName; symbol=tokenSymbol; }
2,077,450
[ 1, 2503, 19527, 7712, 2973, 326, 3844, 18305, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 3155, 12, 1080, 1147, 461, 16, 533, 1147, 5335, 16, 2254, 1208, 3088, 1283, 13, 1071, 288, 203, 202, 202, 529, 33, 2316, 461, 31, 203, 202, 202, 7175, 33, 2316, 5335, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-09 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.11; 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; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 9; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != -1 || a != MIN_INT256); return a / b; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Konsato is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) private _isSniper; bool private _swapping; uint256 private _launchTime; address public feeWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 private _buyMarketingFee; uint256 private _buyLiquidityFee; uint256 private _buyDevFee; uint256 public sellTotalFees; uint256 private _sellMarketingFee; uint256 private _sellLiquidityFee; uint256 private _sellDevFee; uint256 private _tokensForMarketing; uint256 private _tokensForLiquidity; uint256 private _tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event feeWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Konsato", "KONSATO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 buyMarketingFee = 2; uint256 buyLiquidityFee = 3; uint256 buyDevFee = 8; uint256 sellMarketingFee = 2; uint256 sellLiquidityFee = 3; uint256 sellDevFee = 8; uint256 totalSupply = 1e18 * 1e9; maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 3 / 100; // 3% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; feeWallet = address(owner()); // set as fee wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; _launchTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000) / 1e9, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * 1e9; } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * 1e9; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _buyMarketingFee = marketingFee; _buyLiquidityFee = liquidityFee; _buyDevFee = devFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function updateSellFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _sellMarketingFee = marketingFee; _sellLiquidityFee = liquidityFee; _sellDevFee = devFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; require(sellTotalFees <= 15, "Must keep fees at 15% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateFeeWallet(address newWallet) external onlyOwner { emit feeWalletUpdated(newWallet, feeWallet); feeWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { _isSniper[snipers_[i]] = true; } } } function delSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { _isSniper[snipers_[i]] = false; } } function isSniper(address addr) public view returns (bool) { return _isSniper[addr]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } // when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } // when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; if (contractBalance == 0 || totalTokensToSwap == 0) return; if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * _tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; _swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; _tokensForLiquidity = 0; _tokensForMarketing = 0; _tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function withdrawFees() external { payable(feeWallet).transfer(address(this).balance); } receive() external payable {} }
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract Konsato is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) private _isSniper; bool private _swapping; uint256 private _launchTime; address public feeWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 private _buyMarketingFee; uint256 private _buyLiquidityFee; uint256 private _buyDevFee; uint256 public sellTotalFees; uint256 private _sellMarketingFee; uint256 private _sellLiquidityFee; uint256 private _sellDevFee; uint256 private _tokensForMarketing; uint256 private _tokensForLiquidity; uint256 private _tokensForDev; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event feeWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Konsato", "KONSATO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 buyMarketingFee = 2; uint256 buyLiquidityFee = 3; uint256 buyDevFee = 8; uint256 sellMarketingFee = 2; uint256 sellLiquidityFee = 3; uint256 sellDevFee = 8; uint256 totalSupply = 1e18 * 1e9; _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } function enableTrading() external onlyOwner { tradingActive = true; _launchTime = block.timestamp; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000) / 1e9, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * 1e9; } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * 1e9; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _buyMarketingFee = marketingFee; _buyLiquidityFee = liquidityFee; _buyDevFee = devFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function updateSellFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _sellMarketingFee = marketingFee; _sellLiquidityFee = liquidityFee; _sellDevFee = devFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; require(sellTotalFees <= 15, "Must keep fees at 15% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateFeeWallet(address newWallet) external onlyOwner { emit feeWalletUpdated(newWallet, feeWallet); feeWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { _isSniper[snipers_[i]] = true; } } } function setSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { _isSniper[snipers_[i]] = true; } } } function setSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { _isSniper[snipers_[i]] = true; } } } function delSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { _isSniper[snipers_[i]] = false; } } function delSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { _isSniper[snipers_[i]] = false; } } function isSniper(address addr) public view returns (bool) { return _isSniper[addr]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, owner(), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; if (contractBalance == 0 || totalTokensToSwap == 0) return; if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; _swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; _tokensForLiquidity = 0; _tokensForMarketing = 0; _tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; if (contractBalance == 0 || totalTokensToSwap == 0) return; if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; _swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; _tokensForLiquidity = 0; _tokensForMarketing = 0; _tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * _tokensForLiquidity / totalTokensToSwap / 2; function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; if (contractBalance == 0 || totalTokensToSwap == 0) return; if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; _swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; _tokensForLiquidity = 0; _tokensForMarketing = 0; _tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function withdrawFees() external { payable(feeWallet).transfer(address(this).balance); } receive() external payable {} }
15,442,778
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1475, 7008, 31093, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 10461, 77, 457, 31, 203, 565, 1426, 3238, 389, 22270, 1382, 31, 203, 565, 2254, 5034, 3238, 389, 20738, 950, 31, 203, 203, 565, 1758, 1071, 14036, 16936, 31, 203, 377, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 540, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 377, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 70, 9835, 8870, 14667, 31, 203, 377, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 8870, 2 ]
./partial_match/3/0x7dfcAd83cd93E309338705dca079add3A4bD72DC/sources/Nexon.sol
BigPayDay Percentage
uint256 private _bigPayDayPercentage;
5,068,666
[ 1, 9901, 9148, 4245, 21198, 410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 3238, 389, 14002, 9148, 4245, 16397, 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 ]
pragma solidity ^0.4.2; contract Election { //model a candidate struct Candidate{ uint id; string name; uint voteCount; } //Store accts that have voted mapping(address => bool) public voters; //store candidates //fetch candidates mapping(uint => Candidate) public candidates; //store candidates count uint public candidatesCount; uint public commitPhaseEndTime; //uint public initialTime; bool public timeOver; uint public currentTime; //uint voteFee = 0.5 ether; //voted event event votedEvent ( uint indexed _candidateId ); //event timeUp event timeEvent (); constructor() public { uint _commitPhaseLengthInSeconds; //if (_commitPhaseLengthInSeconds < 30) { // throw; //} _commitPhaseLengthInSeconds = 71000; //currentTime = now; commitPhaseEndTime = now + _commitPhaseLengthInSeconds * 1 seconds; addCandidate("candidate1"); addCandidate("candidate2"); addCandidate("candidate3"); addCandidate("candidate4"); } function addCandidate (string _name) private { candidatesCount++; candidates[candidatesCount] = Candidate(candidatesCount, _name,0); } function vote (uint _candidateId) public { // require that voting time is on if (now > commitPhaseEndTime) revert(); // require that they havent voted before require(!voters[msg.sender]); // require a valid candidate require(_candidateId > 0 && _candidateId <= candidatesCount); // require voteFee is paid //require(msg.value == voteFee); //record that voter has voted voters[msg.sender] = true; // update candidate vote count candidates[_candidateId].voteCount ++; //trigger voted event votedEvent(_candidateId); } function nowTime () public returns(uint) { currentTime = now; return currentTime; } function timeOut () public returns(bool) { if (now > commitPhaseEndTime) { timeOver = true; return timeOver; } else { timeOver = false; return timeOver; } timeEvent(); } }
require that voting time is on require that they havent voted before require a valid candidate require voteFee is paidrequire(msg.value == voteFee);record that voter has voted update candidate vote counttrigger voted event
function vote (uint _candidateId) public { if (now > commitPhaseEndTime) revert(); require(!voters[msg.sender]); require(_candidateId > 0 && _candidateId <= candidatesCount); voters[msg.sender] = true; candidates[_candidateId].voteCount ++; votedEvent(_candidateId); }
12,973,128
[ 1, 6528, 716, 331, 17128, 813, 353, 603, 2583, 716, 2898, 10677, 616, 331, 16474, 1865, 2583, 279, 923, 5500, 2583, 12501, 14667, 353, 30591, 6528, 12, 3576, 18, 1132, 422, 12501, 14667, 1769, 3366, 716, 331, 20005, 711, 331, 16474, 1089, 5500, 12501, 1056, 10668, 331, 16474, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 12501, 261, 11890, 389, 19188, 548, 13, 1071, 288, 203, 202, 202, 430, 261, 3338, 405, 3294, 11406, 25255, 13, 15226, 5621, 203, 202, 202, 6528, 12, 5, 90, 352, 414, 63, 3576, 18, 15330, 19226, 203, 203, 202, 202, 6528, 24899, 19188, 548, 405, 374, 597, 389, 19188, 548, 1648, 7965, 1380, 1769, 203, 203, 202, 202, 90, 352, 414, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 203, 202, 202, 21635, 63, 67, 19188, 548, 8009, 25911, 1380, 965, 31, 203, 203, 202, 202, 90, 16474, 1133, 24899, 19188, 548, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xe27202685EC69e705283e88394bFe47dee972718/sources/contracts/OlympusAuthority.sol
========== STATE VARIABLES ========== */ ========== Constructor ========== */
) OlympusAccessControlled(IOlympusAuthority(address(this))) { governor = _governor; emit GovernorPushed(address(0), governor, true); guardian = _guardian; emit GuardianPushed(address(0), guardian, true); policy = _policy; emit PolicyPushed(address(0), policy, true); vault = _vault; emit VaultPushed(address(0), vault, true); }
1,893,608
[ 1, 1432, 631, 7442, 22965, 55, 422, 1432, 342, 422, 1432, 11417, 422, 1432, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 531, 715, 1291, 407, 16541, 1259, 12, 4294, 715, 1291, 407, 10962, 12, 2867, 12, 2211, 20349, 288, 203, 3639, 314, 1643, 29561, 273, 389, 75, 1643, 29561, 31, 203, 3639, 3626, 611, 1643, 29561, 7621, 329, 12, 2867, 12, 20, 3631, 314, 1643, 29561, 16, 638, 1769, 203, 3639, 11026, 2779, 273, 389, 24594, 2779, 31, 203, 3639, 3626, 22809, 2779, 7621, 329, 12, 2867, 12, 20, 3631, 11026, 2779, 16, 638, 1769, 203, 3639, 3329, 273, 389, 5086, 31, 203, 3639, 3626, 7436, 7621, 329, 12, 2867, 12, 20, 3631, 3329, 16, 638, 1769, 203, 3639, 9229, 273, 389, 26983, 31, 203, 3639, 3626, 17329, 7621, 329, 12, 2867, 12, 20, 3631, 9229, 16, 638, 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 ]
/* APDPH GoldC Token */ pragma solidity ^0.6.12; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return success true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return success true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return success 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 addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return success 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[] memory addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } /** * @dev A Whitelist contract that can be locked and unlocked. Provides a modifier * to check for locked state plus functions and events. The contract is never locked for * whitelisted addresses. The contracts starts off unlocked and can be locked and * then unlocked a single time. Once unlocked, the contract can never be locked back. * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract LockableWhitelisted is Whitelist { event Locked(); event Unlocked(); bool public locked = false; bool private unlockedOnce = false; /** * @dev Modifier to make a function callable only when the contract is not locked * or the caller is whitelisted. */ modifier whenNotLocked(address _address) { require(!locked || whitelist[_address]); _; } /** * @dev Returns true if the specified address is whitelisted. * @param _address The address to check for whitelisting status. */ function isWhitelisted(address _address) public view returns (bool) { return whitelist[_address]; } /** * @dev Called by the owner to lock. */ function lock() onlyOwner public { require(!unlockedOnce); if (!locked) { locked = true; emit Locked(); } } /** * @dev Called by the owner to unlock. */ function unlock() onlyOwner public { if (locked) { locked = false; unlockedOnce = true; emit Unlocked(); } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ abstract contract ERC20Basic { function totalSupply() public virtual view returns (uint256); function balanceOf(address who) public virtual view returns (uint256); function transfer(address to, uint256 value) public virtual returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public override view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return balance An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public override view returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public override virtual returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { 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 { 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); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ abstract contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public virtual view returns (uint256); function transferFrom(address from, address to, uint256 value) public virtual returns (bool); function approve(address spender, uint256 value) public virtual returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string memory _name, string memory _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public override virtual returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public override virtual 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 override view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public virtual returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public virtual returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Standard ERC20 Token, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Main contract * @dev ERC20 Token with ownership transferability and airdrop */ contract GoldCToken is BurnableToken, MintableToken, DetailedERC20, LockableWhitelisted { uint256 constant internal DECIMALS = 18; constructor (uint256 _initialSupply) public BurnableToken() MintableToken() DetailedERC20('MDCONTRACT - Token Contract', 'MDCTR', uint8(DECIMALS)) LockableWhitelisted() { require(_initialSupply > 0); mint(owner, _initialSupply); finishMinting(); addAddressToWhitelist(owner); // lock(); /* init lock disabled */ } function transfer(address _to, uint256 _value) public override(BasicToken, ERC20Basic) whenNotLocked(msg.sender) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public override(ERC20, StandardToken) whenNotLocked(_from) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public override(ERC20, StandardToken) whenNotLocked(msg.sender) returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public override whenNotLocked(msg.sender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public override whenNotLocked(msg.sender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } function transferOwnership(address _newOwner) public override onlyOwner { if (owner != _newOwner) { addAddressToWhitelist(_newOwner); removeAddressFromWhitelist(owner); } super.transferOwnership(_newOwner); } /** * @dev Transfers the same amount of tokens to up to 200 specified addresses. * If the sender runs out of balance then the entire transaction fails. * @param _to The addresses to transfer to. * @param _value The amount to be transferred to each address. */ function airdrop(address[] memory _to, uint256 _value) public whenNotLocked(msg.sender) { require(_to.length <= 200); require(balanceOf(msg.sender) >= _value.mul(_to.length)); for (uint i = 0; i < _to.length; i++) { transfer(_to[i], _value); } } /** * @dev Transfers a variable amount of tokens to up to 200 specified addresses. * If the sender runs out of balance then the entire transaction fails. * For each address a value must be specified. * @param _to The addresses to transfer to. * @param _values The amounts to be transferred to the addresses. */ function multiTransfer(address[] memory _to, uint256[] memory _values) public whenNotLocked(msg.sender) { require(_to.length <= 200); require(_to.length == _values.length); for (uint i = 0; i < _to.length; i++) { transfer(_to[i], _values[i]); } } }
* @title SafeMath @dev Math operations with safety checks that throw on error/
library SafeMath { APDPH GoldC Token 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 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; } }
5,854,104
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 604, 603, 555, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 203, 14410, 8640, 44, 611, 1673, 39, 3155, 203, 203, 225, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 69, 422, 374, 13, 288, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 565, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 565, 1815, 12, 71, 342, 279, 422, 324, 1769, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 225, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 69, 422, 374, 13, 288, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 565, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 565, 1815, 12, 71, 342, 279, 422, 324, 1769, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 225, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 225, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 1815, 12, 70, 1648, 279, 1769, 203, 565, 327, 279, 300, 324, 31, 203, 225, 289, 203, 203, 225, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 276, 2 ]
pragma solidity ^0.4.11; // File: @laborx/solidity-shared-lib/contracts/ERC20Interface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Defines an interface for EIP20 token smart contract contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() public view returns (uint8); function totalSupply() public view returns (uint256 supply); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); } // File: contracts/assets/ChronoBankAssetChainableInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankAssetChainableInterface { function assetType() public pure returns (bytes32); function getPreviousAsset() public view returns (ChronoBankAssetChainableInterface); function getNextAsset() public view returns (ChronoBankAssetChainableInterface); function getChainedAssets() public view returns (bytes32[] _types, address[] _assets); function getAssetByType(bytes32 _assetType) public view returns (address); function chainAssets(ChronoBankAssetChainableInterface[] _assets) external returns (bool); function __chainAssetsFromIdx(ChronoBankAssetChainableInterface[] _assets, uint _startFromIdx) external returns (bool); function finalizeAssetChaining() public; } // File: contracts/assets/ChronoBankAssetUtils.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; library ChronoBankAssetUtils { uint constant ASSETS_CHAIN_MAX_LENGTH = 20; function getChainedAssets(ChronoBankAssetChainableInterface _asset) public view returns (bytes32[] _types, address[] _assets) { bytes32[] memory _tempTypes = new bytes32[](ASSETS_CHAIN_MAX_LENGTH); address[] memory _tempAssets = new address[](ASSETS_CHAIN_MAX_LENGTH); ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); uint _counter = 0; do { _tempTypes[_counter] = _next.assetType(); _tempAssets[_counter] = address(_next); _counter += 1; _next = _next.getNextAsset(); } while (address(_next) != 0x0); _types = new bytes32[](_counter); _assets = new address[](_counter); for (uint _assetIdx = 0; _assetIdx < _counter; ++_assetIdx) { _types[_assetIdx] = _tempTypes[_assetIdx]; _assets[_assetIdx] = _tempAssets[_assetIdx]; } } function getAssetByType(ChronoBankAssetChainableInterface _asset, bytes32 _assetType) public view returns (address) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (_next.assetType() == _assetType) { return address(_next); } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function containsAssetInChain(ChronoBankAssetChainableInterface _asset, address _checkAsset) public view returns (bool) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (address(_next) == _checkAsset) { return true; } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function getHeadAsset(ChronoBankAssetChainableInterface _asset) public view returns (ChronoBankAssetChainableInterface) { ChronoBankAssetChainableInterface _head = _asset; ChronoBankAssetChainableInterface _previousAsset; do { _previousAsset = _head.getPreviousAsset(); if (address(_previousAsset) == 0x0) { return _head; } _head = _previousAsset; } while (true); } } // File: @laborx/solidity-eventshistory-lib/contracts/EventsHistorySourceAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title EventsHistory Source Adapter. */ contract EventsHistorySourceAdapter { // It is address of MultiEventsHistory caller assuming we are inside of delegate call. function _self() internal view returns (address) { return msg.sender; } } // File: @laborx/solidity-eventshistory-lib/contracts/MultiEventsHistoryAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title General MultiEventsHistory user. */ contract MultiEventsHistoryAdapter is EventsHistorySourceAdapter { address internal localEventsHistory; event ErrorCode(address indexed self, uint errorCode); function getEventsHistory() public view returns (address) { address _eventsHistory = localEventsHistory; return _eventsHistory != 0x0 ? _eventsHistory : this; } function emitErrorCode(uint _errorCode) public { emit ErrorCode(_self(), _errorCode); } function _setEventsHistory(address _eventsHistory) internal returns (bool) { localEventsHistory = _eventsHistory; return true; } function _emitErrorCode(uint _errorCode) internal returns (uint) { MultiEventsHistoryAdapter(getEventsHistory()).emitErrorCode(_errorCode); return _errorCode; } } // File: contracts/ChronoBankPlatformEmitter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /// @title ChronoBank Platform Emitter. /// /// Contains all the original event emitting function definitions and events. /// In case of new events needed later, additional emitters can be developed. /// All the functions is meant to be called using delegatecall. contract ChronoBankPlatformEmitter is MultiEventsHistoryAdapter { event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference); event Issue(bytes32 indexed symbol, uint value, address indexed by); event Revoke(bytes32 indexed symbol, uint value, address indexed by); event RevokeExternal(bytes32 indexed symbol, uint value, address indexed by, string externalReference); event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol); event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value); event Recovery(address indexed from, address indexed to, address by); function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) public { emit Transfer(_from, _to, _symbol, _value, _reference); } function emitIssue(bytes32 _symbol, uint _value, address _by) public { emit Issue(_symbol, _value, _by); } function emitRevoke(bytes32 _symbol, uint _value, address _by) public { emit Revoke(_symbol, _value, _by); } function emitRevokeExternal(bytes32 _symbol, uint _value, address _by, string _externalReference) public { emit RevokeExternal(_symbol, _value, _by, _externalReference); } function emitOwnershipChange(address _from, address _to, bytes32 _symbol) public { emit OwnershipChange(_from, _to, _symbol); } function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) public { emit Approve(_from, _spender, _symbol, _value); } function emitRecovery(address _from, address _to, address _by) public { emit Recovery(_from, _to, _by); } } // File: contracts/ChronoBankPlatformInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; contract ChronoBankPlatformInterface is ChronoBankPlatformEmitter { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public view returns (bytes32); function symbolsCount() public view returns (uint); function isCreated(bytes32 _symbol) public view returns(bool); function isOwner(address _owner, bytes32 _symbol) public view returns(bool); function owner(bytes32 _symbol) public view returns(address); function setProxy(address _address, bytes32 _symbol) public returns(uint errorCode); function name(bytes32 _symbol) public view returns(string); function totalSupply(bytes32 _symbol) public view returns(uint); function balanceOf(address _holder, bytes32 _symbol) public view returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns(uint); function baseUnit(bytes32 _symbol) public view returns(uint8); function description(bytes32 _symbol) public view returns(string); function isReissuable(bytes32 _symbol) public view returns(bool); function blockNumber(bytes32 _symbol) public view returns (uint); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber) public returns(uint errorCode); function issueAssetWithInitialReceiver(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account) public returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public returns (uint); function revokeAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint); function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool); function isDesignatedAssetManager(address _account, bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns(uint errorCode); } // File: contracts/ChronoBankAssetInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetInterface { function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns(bool); function __process(bytes /*_data*/, address /*_sender*/) public payable { revert("ASSET_PROCESS_NOT_SUPPORTED"); } } // File: contracts/ChronoBankAssetProxy.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ERC20 is ERC20Interface {} contract ChronoBankAsset is ChronoBankAssetInterface {} /// @title ChronoBank Asset Proxy. /// /// Proxy implements ERC20 interface and acts as a gateway to a single platform asset. /// Proxy adds symbol and caller(sender) when forwarding requests to platform. /// Every request that is made by caller first sent to the specific asset implementation /// contract, which then calls back to be forwarded onto platform. /// /// Calls flow: Caller -> /// Proxy.func(...) -> /// Asset.__func(..., Caller.address) -> /// Proxy.__func(..., Caller.address) -> /// Platform.proxyFunc(..., symbol, Caller.address) /// /// Asset implementation contract is mutable, but each user have an option to stick with /// old implementation, through explicit decision made in timely manner, if he doesn't agree /// with new rules. /// Each user have a possibility to upgrade to latest asset contract implementation, without the /// possibility to rollback. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankAssetProxy is ERC20 { /// @dev Supports ChronoBankPlatform ability to return error codes from methods uint constant OK = 1; /// @dev Assigned platform, immutable. ChronoBankPlatform public chronoBankPlatform; /// @dev Assigned symbol, immutable. bytes32 public smbl; /// @dev Assigned name, immutable. string public name; /// @dev Assigned symbol (from ERC20 standard), immutable string public symbol; /// @notice Sets platform address, assigns symbol and name. /// Can be set only once. /// @param _chronoBankPlatform platform contract address. /// @param _symbol assigned symbol. /// @param _name assigned name. /// @return success. function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) public returns (bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @dev Only platform is allowed to call. modifier onlyChronoBankPlatform { if (msg.sender == address(chronoBankPlatform)) { _; } } /// @dev Only current asset owner is allowed to call. modifier onlyAssetOwner { if (chronoBankPlatform.isOwner(msg.sender, smbl)) { _; } } /// @dev Returns asset implementation contract for current caller. /// @return asset implementation contract. function _getAsset() internal view returns (ChronoBankAsset) { return ChronoBankAsset(getVersionFor(msg.sender)); } /// @notice Returns asset total supply. /// @return asset total supply. function totalSupply() public view returns (uint) { return chronoBankPlatform.totalSupply(smbl); } /// @notice Returns asset balance for a particular holder. /// @param _owner holder address. /// @return holder balance. function balanceOf(address _owner) public view returns (uint) { return chronoBankPlatform.balanceOf(_owner, smbl); } /// @notice Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @return holder to spender allowance. function allowance(address _from, address _spender) public view returns (uint) { return chronoBankPlatform.allowance(_from, _spender, smbl); } /// @notice Returns asset decimals. /// @return asset decimals. function decimals() public view returns (uint8) { return chronoBankPlatform.baseUnit(smbl); } /// @notice Transfers asset balance from the caller to specified receiver. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transfer(address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } } /// @notice Transfers asset balance from the caller to specified receiver adding specified comment. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @return success. function transferWithReference(address _to, uint _value, string _reference) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } } /// @notice Resolves asset implementation contract for the caller and forwards there arguments along with /// the caller address. /// @return success. function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /// @notice Performs transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferWithReference( address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /// @notice Performs allowance transfer of asset balance between holders. /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } } /// @notice Performs allowance transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferFromWithReference( address _from, address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /// @notice Sets asset spending allowance for a specified spender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @return success. function approve(address _spender, uint _value) public returns (bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } } /// @notice Performs allowance setting call on the platform by the name of specified sender. /// Can only be called by asset implementation contract assigned to sender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _sender initial caller. /// @return success. function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /// @notice Emits ERC20 Transfer event on this contract. /// Can only be, and, called by assigned platform when asset transfer happens. function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform public { emit Transfer(_from, _to, _value); } /// @notice Emits ERC20 Approval event on this contract. /// Can only be, and, called by assigned platform when asset allowance set happens. function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform public { emit Approval(_from, _spender, _value); } /// @notice Resolves asset implementation contract for the caller and forwards there transaction data, /// along with the value. This allows for proxy interface growth. function () public payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /// @dev Indicates an upgrade freeze-time start, and the next asset implementation contract. event UpgradeProposal(address newVersion); /// @dev Current asset implementation contract address. address latestVersion; /// @dev Proposed next asset implementation contract address. address pendingVersion; /// @dev Upgrade freeze-time start. uint pendingVersionTimestamp; /// @dev Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; /// @dev Asset implementation contract address that user decided to stick with. /// 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /// @dev Only asset implementation contract assigned to sender is allowed to call. modifier onlyAccess(address _sender) { address _versionFor = getVersionFor(_sender); if (msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender) ) { _; } } /// @notice Returns asset implementation contract address assigned to sender. /// @param _sender sender address. /// @return asset implementation contract address. function getVersionFor(address _sender) public view returns (address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /// @notice Returns current asset implementation contract address. /// @return asset implementation contract address. function getLatestVersion() public view returns (address) { return latestVersion; } /// @notice Returns proposed next asset implementation contract address. /// @return asset implementation contract address. function getPendingVersion() public view returns (address) { return pendingVersion; } /// @notice Returns upgrade freeze-time start. /// @return freeze-time start. function getPendingVersionTimestamp() public view returns (uint) { return pendingVersionTimestamp; } /// @notice Propose next asset implementation contract address. /// Can only be called by current asset owner. /// Note: freeze-time should not be applied for the initial setup. /// @param _newVersion asset implementation contract address. /// @return success. function proposeUpgrade(address _newVersion) onlyAssetOwner public returns (bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; emit UpgradeProposal(_newVersion); return true; } /// @notice Cancel the pending upgrade process. /// Can only be called by current asset owner. /// @return success. function purgeUpgrade() public onlyAssetOwner returns (bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Finalize an upgrade process setting new asset implementation contract address. /// Can only be called after an upgrade freeze-time. /// @return success. function commitUpgrade() public returns (bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Disagree with proposed upgrade, and stick with current asset implementation /// until further explicit agreement to upgrade. /// @return success. function optOut() public returns (bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /// @notice Implicitly agree to upgrade to current and future asset implementation upgrades, /// until further explicit disagreement. /// @return success. function optIn() public returns (bool) { delete userOptOutVersion[msg.sender]; return true; } } // File: @laborx/solidity-shared-lib/contracts/Owned.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Owned contract with safe ownership pass. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public contractOwner; address public pendingContractOwner; modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } constructor() public { contractOwner = msg.sender; } /// @notice Prepares ownership pass. /// Can only be called by current owner. /// @param _to address of the next owner. /// @return success. function changeContractOwnership(address _to) public onlyContractOwner returns (bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /// @notice Finalize ownership pass. /// Can only be called by pending owner. /// @return success. function claimContractOwnership() public returns (bool) { if (msg.sender != pendingContractOwner) { return false; } emit OwnershipTransferred(contractOwner, pendingContractOwner); contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } /// @notice 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 onlyContractOwner returns (bool) { if (newOwner == 0x0) { return false; } emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @dev Backward compatibility only. /// @param newOwner The address to transfer ownership to. function transferContractOwnership(address newOwner) public returns (bool) { return transferOwnership(newOwner); } /// @notice Withdraw given tokens from contract to owner. /// This method is only allowed for contact owner. function withdrawTokens(address[] tokens) public onlyContractOwner { address _contractOwner = contractOwner; for (uint i = 0; i < tokens.length; i++) { ERC20Interface token = ERC20Interface(tokens[i]); uint balance = token.balanceOf(this); if (balance > 0) { token.transfer(_contractOwner, balance); } } } /// @notice Withdraw ether from contract to owner. /// This method is only allowed for contact owner. function withdrawEther() public onlyContractOwner { uint balance = address(this).balance; if (balance > 0) { contractOwner.transfer(balance); } } /// @notice Transfers ether to another address. /// Allowed only for contract owners. /// @param _to recepient address /// @param _value wei to transfer; must be less or equal to total balance on the contract function transferEther(address _to, uint256 _value) public onlyContractOwner { require(_to != 0x0, "INVALID_ETHER_RECEPIENT_ADDRESS"); if (_value > address(this).balance) { revert("INVALID_VALUE_TO_TRANSFER_ETHER"); } _to.transfer(_value); } } // File: @laborx/solidity-storage-lib/contracts/Storage.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract Manager { function isAllowed(address _actor, bytes32 _role) public view returns (bool); function hasAccess(address _actor) public view returns (bool); } contract Storage is Owned { struct Crate { mapping(bytes32 => uint) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(bytes32 => int) ints; mapping(bytes32 => uint8) uint8s; mapping(bytes32 => bytes32) bytes32s; mapping(bytes32 => AddressUInt8) addressUInt8s; mapping(bytes32 => string) strings; } struct AddressUInt8 { address _address; uint8 _uint8; } mapping(bytes32 => Crate) internal crates; Manager public manager; modifier onlyAllowed(bytes32 _role) { if (!(msg.sender == address(this) || manager.isAllowed(msg.sender, _role))) { revert("STORAGE_FAILED_TO_ACCESS_PROTECTED_FUNCTION"); } _; } function setManager(Manager _manager) external onlyContractOwner returns (bool) { manager = _manager; return true; } function setUInt(bytes32 _crate, bytes32 _key, uint _value) public onlyAllowed(_crate) { _setUInt(_crate, _key, _value); } function _setUInt(bytes32 _crate, bytes32 _key, uint _value) internal { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) public view returns (uint) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) public onlyAllowed(_crate) { _setAddress(_crate, _key, _value); } function _setAddress(bytes32 _crate, bytes32 _key, address _value) internal { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) public view returns (address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) public onlyAllowed(_crate) { _setBool(_crate, _key, _value); } function _setBool(bytes32 _crate, bytes32 _key, bool _value) internal { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) public view returns (bool) { return crates[_crate].bools[_key]; } function setInt(bytes32 _crate, bytes32 _key, int _value) public onlyAllowed(_crate) { _setInt(_crate, _key, _value); } function _setInt(bytes32 _crate, bytes32 _key, int _value) internal { crates[_crate].ints[_key] = _value; } function getInt(bytes32 _crate, bytes32 _key) public view returns (int) { return crates[_crate].ints[_key]; } function setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) public onlyAllowed(_crate) { _setUInt8(_crate, _key, _value); } function _setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) internal { crates[_crate].uint8s[_key] = _value; } function getUInt8(bytes32 _crate, bytes32 _key) public view returns (uint8) { return crates[_crate].uint8s[_key]; } function setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) public onlyAllowed(_crate) { _setBytes32(_crate, _key, _value); } function _setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) internal { crates[_crate].bytes32s[_key] = _value; } function getBytes32(bytes32 _crate, bytes32 _key) public view returns (bytes32) { return crates[_crate].bytes32s[_key]; } function setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) public onlyAllowed(_crate) { _setAddressUInt8(_crate, _key, _value, _value2); } function _setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) internal { crates[_crate].addressUInt8s[_key] = AddressUInt8(_value, _value2); } function getAddressUInt8(bytes32 _crate, bytes32 _key) public view returns (address, uint8) { return (crates[_crate].addressUInt8s[_key]._address, crates[_crate].addressUInt8s[_key]._uint8); } function setString(bytes32 _crate, bytes32 _key, string _value) public onlyAllowed(_crate) { _setString(_crate, _key, _value); } function _setString(bytes32 _crate, bytes32 _key, string _value) internal { crates[_crate].strings[_key] = _value; } function getString(bytes32 _crate, bytes32 _key) public view returns (string) { return crates[_crate].strings[_key]; } } // File: @laborx/solidity-storage-lib/contracts/StorageInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; library StorageInterface { struct Config { Storage store; bytes32 crate; } struct UInt { bytes32 id; } struct UInt8 { bytes32 id; } struct Int { bytes32 id; } struct Address { bytes32 id; } struct Bool { bytes32 id; } struct Bytes32 { bytes32 id; } struct String { bytes32 id; } struct Mapping { bytes32 id; } struct StringMapping { String id; } struct UIntBoolMapping { Bool innerMapping; } struct UIntUIntMapping { Mapping innerMapping; } struct UIntBytes32Mapping { Mapping innerMapping; } struct UIntAddressMapping { Mapping innerMapping; } struct UIntEnumMapping { Mapping innerMapping; } struct AddressBoolMapping { Mapping innerMapping; } struct AddressUInt8Mapping { bytes32 id; } struct AddressUIntMapping { Mapping innerMapping; } struct AddressBytes32Mapping { Mapping innerMapping; } struct AddressAddressMapping { Mapping innerMapping; } struct Bytes32UIntMapping { Mapping innerMapping; } struct Bytes32UInt8Mapping { UInt8 innerMapping; } struct Bytes32BoolMapping { Bool innerMapping; } struct Bytes32Bytes32Mapping { Mapping innerMapping; } struct Bytes32AddressMapping { Mapping innerMapping; } struct Bytes32UIntBoolMapping { Bool innerMapping; } struct AddressAddressUInt8Mapping { Mapping innerMapping; } struct AddressAddressUIntMapping { Mapping innerMapping; } struct AddressUIntUIntMapping { Mapping innerMapping; } struct AddressUIntUInt8Mapping { Mapping innerMapping; } struct AddressBytes32Bytes32Mapping { Mapping innerMapping; } struct AddressBytes4BoolMapping { Mapping innerMapping; } struct AddressBytes4Bytes32Mapping { Mapping innerMapping; } struct UIntAddressUIntMapping { Mapping innerMapping; } struct UIntAddressAddressMapping { Mapping innerMapping; } struct UIntAddressBoolMapping { Mapping innerMapping; } struct UIntUIntAddressMapping { Mapping innerMapping; } struct UIntUIntBytes32Mapping { Mapping innerMapping; } struct UIntUIntUIntMapping { Mapping innerMapping; } struct Bytes32UIntUIntMapping { Mapping innerMapping; } struct AddressUIntUIntUIntMapping { Mapping innerMapping; } struct AddressUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct UIntAddressAddressBoolMapping { Bool innerMapping; } struct UIntUIntUIntBytes32Mapping { Mapping innerMapping; } struct Bytes32UIntUIntUIntMapping { Mapping innerMapping; } bytes32 constant SET_IDENTIFIER = "set"; struct Set { UInt count; Mapping indexes; Mapping values; } struct AddressesSet { Set innerSet; } struct CounterSet { Set innerSet; } bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; struct OrderedSet { UInt count; Bytes32 first; Bytes32 last; Mapping nextValues; Mapping previousValues; } struct OrderedUIntSet { OrderedSet innerSet; } struct OrderedAddressesSet { OrderedSet innerSet; } struct Bytes32SetMapping { Set innerMapping; } struct AddressesSetMapping { Bytes32SetMapping innerMapping; } struct UIntSetMapping { Bytes32SetMapping innerMapping; } struct Bytes32OrderedSetMapping { OrderedSet innerMapping; } struct UIntOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } struct AddressOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert(); } } function init(Config storage self, Storage _store, bytes32 _crate) internal { self.store = _store; self.crate = _crate; } function init(UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(Config storage self, UInt storage item, uint _value) internal { self.store.setUInt(self.crate, item.id, _value); } function set(Config storage self, UInt storage item, bytes32 _salt, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, UInt8 storage item, uint8 _value) internal { self.store.setUInt8(self.crate, item.id, _value); } function set(Config storage self, UInt8 storage item, bytes32 _salt, uint8 _value) internal { self.store.setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Int storage item, int _value) internal { self.store.setInt(self.crate, item.id, _value); } function set(Config storage self, Int storage item, bytes32 _salt, int _value) internal { self.store.setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Address storage item, address _value) internal { self.store.setAddress(self.crate, item.id, _value); } function set(Config storage self, Address storage item, bytes32 _salt, address _value) internal { self.store.setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bool storage item, bool _value) internal { self.store.setBool(self.crate, item.id, _value); } function set(Config storage self, Bool storage item, bytes32 _salt, bool _value) internal { self.store.setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bytes32 storage item, bytes32 _value) internal { self.store.setBytes32(self.crate, item.id, _value); } function set(Config storage self, Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, String storage item, string _value) internal { self.store.setString(self.crate, item.id, _value); } function set(Config storage self, String storage item, bytes32 _salt, string _value) internal { self.store.setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Mapping storage item, uint _key, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { self.store.setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(Config storage self, AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(Config storage self, Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(Config storage self, AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(Config storage self, OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(Config storage self, Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(Config storage self, Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(Config storage self, AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(Config storage self, Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(Config storage self, AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(Config storage self, OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(Config storage self, Set storage source, Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(Config storage self, AddressesSet storage source, AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(Config storage self, CounterSet storage source, CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(Config storage self, UInt storage item) internal view returns (uint) { return self.store.getUInt(self.crate, item.id); } function get(Config storage self, UInt storage item, bytes32 salt) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, UInt8 storage item) internal view returns (uint8) { return self.store.getUInt8(self.crate, item.id); } function get(Config storage self, UInt8 storage item, bytes32 salt) internal view returns (uint8) { return self.store.getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Int storage item) internal view returns (int) { return self.store.getInt(self.crate, item.id); } function get(Config storage self, Int storage item, bytes32 salt) internal view returns (int) { return self.store.getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Address storage item) internal view returns (address) { return self.store.getAddress(self.crate, item.id); } function get(Config storage self, Address storage item, bytes32 salt) internal view returns (address) { return self.store.getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bool storage item) internal view returns (bool) { return self.store.getBool(self.crate, item.id); } function get(Config storage self, Bool storage item, bytes32 salt) internal view returns (bool) { return self.store.getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bytes32 storage item) internal view returns (bytes32) { return self.store.getBytes32(self.crate, item.id); } function get(Config storage self, Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, String storage item) internal view returns (string) { return self.store.getString(self.crate, item.id); } function get(Config storage self, String storage item, bytes32 salt) internal view returns (string) { return self.store.getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Mapping storage item, uint _key) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(Config storage self, AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return self.store.getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(Config storage self, Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(Config storage self, AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(Config storage self, AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(Config storage self, Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(Config storage self, Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(Config storage self, OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(Config storage self, Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(Config storage self, Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(Config storage self, AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(Config storage self, CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(Config storage self, Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(Config storage self, Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(Config storage self, AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(Config storage self, CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /** @title Structure to incapsulate and organize iteration through different kinds of collections */ struct Iterator { uint limit; uint valuesLeft; bytes32 currentValue; bytes32 anchorKey; } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(Config storage self, OrderedUIntSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedSet storage item) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(Config storage self, OrderedUIntSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, OrderedAddressesSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (Iterator) { return Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-storage-lib/contracts/StorageContractAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageContractAdapter { StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { StorageInterface.init(store, _store, _crate); } } // File: @laborx/solidity-storage-lib/contracts/StorageInterfaceContract.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageInterfaceContract is StorageContractAdapter, Storage { bytes32 constant SET_IDENTIFIER = "set"; bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert("STORAGE_INTERFACE_CONTRACT_SANITY_CHECK_FAILED"); } } function init(StorageInterface.Config storage self, bytes32 _crate) internal { self.crate = _crate; } function init(StorageInterface.UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(StorageInterface.UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(StorageInterface.AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(StorageInterface.OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, uint _value) internal { _setUInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 _salt, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, uint8 _value) internal { _setUInt8(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 _salt, uint8 _value) internal { _setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, int _value) internal { _setInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 _salt, int _value) internal { _setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, address _value) internal { _setAddress(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 _salt, address _value) internal { _setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bool _value) internal { _setBool(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _salt, bool _value) internal { _setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _value) internal { _setBytes32(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, string _value) internal { _setString(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 _salt, string _value) internal { _setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { _setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(StorageInterface.Config storage self, StorageInterface.Set storage source, StorageInterface.Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(StorageInterface.Config storage self, StorageInterface.AddressesSet storage source, StorageInterface.AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(StorageInterface.Config storage self, StorageInterface.CounterSet storage source, StorageInterface.CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(StorageInterface.Config storage self, StorageInterface.UInt storage item) internal view returns (uint) { return getUInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 salt) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item) internal view returns (uint8) { return getUInt8(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 salt) internal view returns (uint8) { return getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item) internal view returns (int) { return getInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 salt) internal view returns (int) { return getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item) internal view returns (address) { return getAddress(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 salt) internal view returns (address) { return getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item) internal view returns (bool) { return getBool(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 salt) internal view returns (bool) { return getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item) internal view returns (bytes32) { return getBytes32(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.String storage item) internal view returns (string) { return getString(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 salt) internal view returns (string) { return getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /* ITERABLE */ function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (StorageInterface.Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (StorageInterface.Iterator) { return StorageInterface.Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(StorageInterface.Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-shared-lib/contracts/BaseByzantiumRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; /// @title Routing contract that is able to provide a way for delegating invocations with dynamic destination address. contract BaseByzantiumRouter { function() external payable { address _implementation = implementation(); assembly { let calldataMemoryOffset := mload(0x40) mstore(0x40, add(calldataMemoryOffset, calldatasize)) calldatacopy(calldataMemoryOffset, 0x0, calldatasize) let r := delegatecall(sub(gas, 10000), _implementation, calldataMemoryOffset, calldatasize, 0, 0) let returndataMemoryOffset := mload(0x40) mstore(0x40, add(returndataMemoryOffset, returndatasize)) returndatacopy(returndataMemoryOffset, 0x0, returndatasize) switch r case 1 { return(returndataMemoryOffset, returndatasize) } default { revert(0, 0) } } } /// @notice Returns destination address for future calls /// @dev abstract definition. should be implemented in sibling contracts /// @return destination address function implementation() internal view returns (address); } // File: @laborx/solidity-storage-lib/contracts/StorageAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageAdapter { using StorageInterface for *; StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { store.init(_store, _crate); } } // File: contracts/ChronoBankPlatformBackendProvider.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformBackendProvider is Owned { ChronoBankPlatformInterface public platformBackend; constructor(ChronoBankPlatformInterface _platformBackend) public { updatePlatformBackend(_platformBackend); } function updatePlatformBackend(ChronoBankPlatformInterface _updatedPlatformBackend) public onlyContractOwner returns (bool) { require(address(_updatedPlatformBackend) != 0x0, "PLATFORM_BACKEND_PROVIDER_INVALID_PLATFORM_ADDRESS"); platformBackend = _updatedPlatformBackend; return true; } } // File: contracts/ChronoBankPlatformRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformRouterCore { address internal platformBackendProvider; } contract ChronoBankPlatformCore { bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; /// @dev Asset's owner id StorageInterface.Bytes32UIntMapping internal assetOwnerIdStorage; /// @dev Asset's total supply StorageInterface.Bytes32UIntMapping internal assetTotalSupply; /// @dev Asset's name, for information purposes. StorageInterface.StringMapping internal assetName; /// @dev Asset's description, for information purposes. StorageInterface.StringMapping internal assetDescription; /// @dev Indicates if asset have dynamic or fixed supply StorageInterface.Bytes32BoolMapping internal assetIsReissuable; /// @dev Proposed number of decimals StorageInterface.Bytes32UInt8Mapping internal assetBaseUnit; /// @dev Holders wallets partowners StorageInterface.Bytes32UIntBoolMapping internal assetPartowners; /// @dev Holders wallets balance StorageInterface.Bytes32UIntUIntMapping internal assetWalletBalance; /// @dev Holders wallets allowance StorageInterface.Bytes32UIntUIntUIntMapping internal assetWalletAllowance; /// @dev Block number from which asset can be used StorageInterface.Bytes32UIntMapping internal assetBlockNumber; /// @dev Iterable mapping pattern is used for holders. StorageInterface.UInt internal holdersCountStorage; /// @dev Current address of the holder. StorageInterface.UIntAddressMapping internal holdersAddressStorage; /// @dev Addresses that are trusted with recovery proocedure. StorageInterface.UIntAddressBoolMapping internal holdersTrustStorage; /// @dev This is an access address mapping. Many addresses may have access to a single holder. StorageInterface.AddressUIntMapping internal holderIndexStorage; /// @dev List of symbols that exist in a platform StorageInterface.Set internal symbolsStorage; /// @dev Asset symbol to asset proxy mapping. StorageInterface.Bytes32AddressMapping internal proxiesStorage; /// @dev Co-owners of a platform. Has less access rights than a root contract owner StorageInterface.AddressBoolMapping internal partownersStorage; } contract ChronoBankPlatformRouter is BaseByzantiumRouter, ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageAdapter { /// @dev memory layout from Owned contract address public contractOwner; bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; constructor(address _platformBackendProvider) StorageAdapter(Storage(address(this)), CHRONOBANK_PLATFORM_CRATE) public { require(_platformBackendProvider != 0x0, "PLATFORM_ROUTER_INVALID_BACKEND_ADDRESS"); contractOwner = msg.sender; platformBackendProvider = _platformBackendProvider; } function implementation() internal view returns (address) { return ChronoBankPlatformBackendProvider(platformBackendProvider).platformBackend(); } } // File: contracts/lib/SafeMath.sol /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "SAFE_MATH_INVALID_MUL"); 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) { require(b <= a, "SAFE_MATH_INVALID_SUB"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SAFE_MATH_INVALID_ADD"); return c; } } // File: contracts/ChronoBankPlatform.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ProxyEventsEmitter { function emitTransfer(address _from, address _to, uint _value) public; function emitApprove(address _from, address _spender, uint _value) public; } /// @title ChronoBank Platform. /// /// The official ChronoBank assets platform powering TIME and LHT tokens, and possibly /// other unknown tokens needed later. /// Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed /// at some point, all the events keep appearing at the same place. /// /// Every asset is meant to be used through a proxy contract. Only one proxy contract have access /// rights for a particular asset. /// /// Features: transfers, allowances, supply adjustments, lost wallet access recovery. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankPlatform is ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageInterfaceContract, ChronoBankPlatformCore { uint constant OK = 1; using SafeMath for uint; uint constant CHRONOBANK_PLATFORM_SCOPE = 15000; uint constant CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS = CHRONOBANK_PLATFORM_SCOPE + 0; uint constant CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF = CHRONOBANK_PLATFORM_SCOPE + 1; uint constant CHRONOBANK_PLATFORM_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 2; uint constant CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE = CHRONOBANK_PLATFORM_SCOPE + 3; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE = CHRONOBANK_PLATFORM_SCOPE + 4; uint constant CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 5; uint constant CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 6; uint constant CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = CHRONOBANK_PLATFORM_SCOPE + 7; uint constant CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW = CHRONOBANK_PLATFORM_SCOPE + 8; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS = CHRONOBANK_PLATFORM_SCOPE + 9; uint constant CHRONOBANK_PLATFORM_INVALID_NEW_OWNER = CHRONOBANK_PLATFORM_SCOPE + 10; uint constant CHRONOBANK_PLATFORM_ALREADY_TRUSTED = CHRONOBANK_PLATFORM_SCOPE + 11; uint constant CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = CHRONOBANK_PLATFORM_SCOPE + 12; uint constant CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 13; uint constant CHRONOBANK_PLATFORM_INVALID_INVOCATION = CHRONOBANK_PLATFORM_SCOPE + 17; string public version = "0.2.0"; struct TransactionContext { address from; address to; address sender; uint fromHolderId; uint toHolderId; uint senderHolderId; uint balanceFrom; uint balanceTo; uint allowanceValue; } /// @dev Emits Error if called not by asset owner. modifier onlyOwner(bytes32 _symbol) { if (isOwner(msg.sender, _symbol)) { _; } } modifier onlyDesignatedManager(bytes32 _symbol) { if (isDesignatedAssetManager(msg.sender, _symbol)) { _; } } /// @dev UNAUTHORIZED if called not by one of partowners or contract's owner modifier onlyOneOfContractOwners() { if (contractOwner == msg.sender || partowners(msg.sender)) { _; } } /// @dev Emits Error if called not by asset proxy. modifier onlyProxy(bytes32 _symbol) { if (proxies(_symbol) == msg.sender) { _; } } /// @dev Emits Error if _from doesn't trust _to. modifier checkTrust(address _from, address _to) { if (isTrusted(_from, _to)) { _; } } /// @dev Emits Error if asset block number > current block number. modifier onlyAfterBlock(bytes32 _symbol) { if (block.number >= blockNumber(_symbol)) { _; } } constructor() StorageContractAdapter(this, CHRONOBANK_PLATFORM_CRATE) public { } function initStorage() public { init(partownersStorage, "partowners"); init(proxiesStorage, "proxies"); init(symbolsStorage, "symbols"); init(holdersCountStorage, "holdersCount"); init(holderIndexStorage, "holderIndex"); init(holdersAddressStorage, "holdersAddress"); init(holdersTrustStorage, "holdersTrust"); init(assetOwnerIdStorage, "assetOwner"); init(assetTotalSupply, "assetTotalSupply"); init(assetName, "assetName"); init(assetDescription, "assetDescription"); init(assetIsReissuable, "assetIsReissuable"); init(assetBlockNumber, "assetBlockNumber"); init(assetBaseUnit, "assetBaseUnit"); init(assetPartowners, "assetPartowners"); init(assetWalletBalance, "assetWalletBalance"); init(assetWalletAllowance, "assetWalletAllowance"); } /// @dev Asset symbol to asset details. /// @return { /// "_description": "will be null, since cannot store and return dynamic-sized types in storage (fixed in v0.4.24), /// } function assets(bytes32 _symbol) public view returns ( uint _owner, uint _totalSupply, string _name, string _description, bool _isReissuable, uint8 _baseUnit, uint _blockNumber ) { _owner = _assetOwner(_symbol); _totalSupply = totalSupply(_symbol); _name = name(_symbol); _description = description(_symbol); _isReissuable = isReissuable(_symbol); _baseUnit = baseUnit(_symbol); _blockNumber = blockNumber(_symbol); } function holdersCount() public view returns (uint) { return get(store, holdersCountStorage); } function holders(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } function symbols(uint _idx) public view returns (bytes32) { return get(store, symbolsStorage, _idx); } /// @notice Provides a cheap way to get number of symbols registered in a platform /// @return number of symbols function symbolsCount() public view returns (uint) { return count(store, symbolsStorage); } function proxies(bytes32 _symbol) public view returns (address) { return get(store, proxiesStorage, _symbol); } function partowners(address _address) public view returns (bool) { return get(store, partownersStorage, _address); } /// @notice Adds a co-owner of a contract. Might be more than one co-owner /// @dev Allowed to only contract onwer /// @param _partowner a co-owner of a contract /// @return result code of an operation function addPartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, true); return OK; } /// @notice Removes a co-owner of a contract /// @dev Should be performed only by root contract owner /// @param _partowner a co-owner of a contract /// @return result code of an operation function removePartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, false); return OK; } /// @notice Sets EventsHistory contract address. /// @dev Can be set only by owner. /// @param _eventsHistory MultiEventsHistory contract address. /// @return success. function setupEventsHistory(address _eventsHistory) public onlyContractOwner returns (uint errorCode) { _setEventsHistory(_eventsHistory); return OK; } /// @notice Check asset existance. /// @param _symbol asset symbol. /// @return asset existance. function isCreated(bytes32 _symbol) public view returns (bool) { return _assetOwner(_symbol) != 0; } /// @notice Returns asset decimals. /// @param _symbol asset symbol. /// @return asset decimals. function baseUnit(bytes32 _symbol) public view returns (uint8) { return get(store, assetBaseUnit, _symbol); } /// @notice Returns asset name. /// @param _symbol asset symbol. /// @return asset name. function name(bytes32 _symbol) public view returns (string) { return get(store, assetName, _symbol); } /// @notice Returns asset description. /// @param _symbol asset symbol. /// @return asset description. function description(bytes32 _symbol) public view returns (string) { return get(store, assetDescription, _symbol); } /// @notice Returns asset reissuability. /// @param _symbol asset symbol. /// @return asset reissuability. function isReissuable(bytes32 _symbol) public view returns (bool) { return get(store, assetIsReissuable, _symbol); } /// @notice Returns block number from which asset can be used. /// @param _symbol asset symbol. /// @return block number. function blockNumber(bytes32 _symbol) public view returns (uint) { return get(store, assetBlockNumber, _symbol); } /// @notice Returns asset owner address. /// @param _symbol asset symbol. /// @return asset owner address. function owner(bytes32 _symbol) public view returns (address) { return _address(_assetOwner(_symbol)); } /// @notice Check if specified address has asset owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function isOwner(address _owner, bytes32 _symbol) public view returns (bool) { return isCreated(_symbol) && (_assetOwner(_symbol) == getHolderId(_owner)); } /// @notice Checks if a specified address has asset owner or co-owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool) { uint holderId = getHolderId(_owner); return isCreated(_symbol) && (_assetOwner(_symbol) == holderId || get(store, assetPartowners, _symbol, holderId)); } /// @notice Checks if a provided address `_manager` has designated access to asset `_symbol`. /// @param _manager address that will become the asset manager /// @param _symbol asset symbol /// @return true if address is one of designated asset managers, false otherwise function isDesignatedAssetManager(address _manager, bytes32 _symbol) public view returns (bool) { uint managerId = getHolderId(_manager); return isCreated(_symbol) && get(store, assetPartowners, _symbol, managerId); } /// @notice Returns asset total supply. /// @param _symbol asset symbol. /// @return asset total supply. function totalSupply(bytes32 _symbol) public view returns (uint) { return get(store, assetTotalSupply, _symbol); } /// @notice Returns asset balance for a particular holder. /// @param _holder holder address. /// @param _symbol asset symbol. /// @return holder balance. function balanceOf(address _holder, bytes32 _symbol) public view returns (uint) { return _balanceOf(getHolderId(_holder), _symbol); } /// @notice Returns asset balance for a particular holder id. /// @param _holderId holder id. /// @param _symbol asset symbol. /// @return holder balance. function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return get(store, assetWalletBalance, _symbol, _holderId); } /// @notice Returns current address for a particular holder id. /// @param _holderId holder id. /// @return holder address. function _address(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } /// @notice Adds a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function addDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = _createHolderId(_manager); set(store, assetPartowners, _symbol, holderId, true); _emitter().emitOwnershipChange(0x0, _manager, _symbol); return OK; } /// @notice Removes a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function removeDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = getHolderId(_manager); set(store, assetPartowners, _symbol, holderId, false); _emitter().emitOwnershipChange(_manager, 0x0, _symbol); return OK; } /// @notice Sets Proxy contract address for a particular asset. /// @dev Can be set only once for each asset and only by contract owner. /// @param _proxyAddress Proxy contract address. /// @param _symbol asset symbol. /// @return success. function setProxy(address _proxyAddress, bytes32 _symbol) public onlyOneOfContractOwners returns (uint) { if (proxies(_symbol) != 0x0) { return CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS; } set(store, proxiesStorage, _symbol, _proxyAddress); return OK; } /// @notice Performes asset transfer for multiple destinations /// @param addresses list of addresses to receive some amount /// @param values list of asset amounts for according addresses /// @param _symbol asset symbol /// @return { /// "errorCode": "resultCode of an operation", /// "count": "an amount of succeeded transfers" /// } function massTransfer(address[] addresses, uint[] values, bytes32 _symbol) external onlyAfterBlock(_symbol) returns (uint errorCode, uint count) { require(addresses.length == values.length, "Different length of addresses and values for mass transfer"); require(_symbol != 0x0, "Asset's symbol cannot be 0"); return _massTransferDirect(addresses, values, _symbol); } function _massTransferDirect(address[] addresses, uint[] values, bytes32 _symbol) private returns (uint errorCode, uint count) { uint success = 0; TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = _createHolderId(txContext.from); for (uint idx = 0; idx < addresses.length && gasleft() > 110000; idx++) { uint value = values[idx]; if (value == 0) { _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); continue; } txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < value) { _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); continue; } if (txContext.from == addresses[idx]) { _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); continue; } txContext.toHolderId = _createHolderId(addresses[idx]); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); _transferDirect(value, _symbol, txContext); _emitter().emitTransfer(txContext.from, addresses[idx], _symbol, value, ""); success++; } return (OK, success); } /// @dev Transfers asset balance between holders wallets. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _transferDirect( uint _value, bytes32 _symbol, TransactionContext memory _txContext ) internal { set(store, assetWalletBalance, _symbol, _txContext.fromHolderId, _txContext.balanceFrom.sub(_value)); set(store, assetWalletBalance, _symbol, _txContext.toHolderId, _txContext.balanceTo.add(_value)); } /// @dev Transfers asset balance between holders wallets. /// Performs sanity checks and takes care of allowances adjustment. /// /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// /// @return success. function _transfer( uint _value, bytes32 _symbol, string _reference, TransactionContext memory txContext ) internal returns (uint) { // Should not allow to send to oneself. if (txContext.fromHolderId == txContext.toHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough balance. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); } // Should have enough allowance. txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (txContext.fromHolderId != txContext.senderHolderId && txContext.allowanceValue < _value ) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE); } _transferDirect(_value, _symbol, txContext); // Adjust allowance. _decrementWalletAllowance(_value, _symbol, txContext); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitTransfer(txContext.from, txContext.to, _symbol, _value, _reference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _decrementWalletAllowance( uint _value, bytes32 _symbol, TransactionContext memory txContext ) private { if (txContext.fromHolderId != txContext.senderHolderId) { set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, txContext.allowanceValue.sub(_value)); } } /// @dev Transfers asset balance between holders wallets. /// Can only be called by asset proxy. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender transfer initiator address. /// /// @return success. function proxyTransferWithReference( address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _sender; txContext.senderHolderId = getHolderId(_sender); txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = txContext.senderHolderId; return _transfer(_value, _symbol, _reference, txContext); } /// @dev Ask asset Proxy contract to emit ERC20 compliant Transfer event. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _proxyTransferEvent(uint _value, bytes32 _symbol, TransactionContext memory txContext) internal { address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitTransfer(txContext.from, txContext.to, _value); } } /// @notice Returns holder id for the specified address. /// @param _holder holder address. /// @return holder id. function getHolderId(address _holder) public view returns (uint) { return get(store, holderIndexStorage, _holder); } /// @dev Returns holder id for the specified address, creates it if needed. /// @param _holder holder address. /// @return holder id. function _createHolderId(address _holder) internal returns (uint) { uint _holderId = getHolderId(_holder); if (_holderId == 0) { _holderId = holdersCount() + 1; set(store, holderIndexStorage, _holder, _holderId); set(store, holdersAddressStorage, _holderId, _holder); set(store, holdersCountStorage, _holderId); } return _holderId; } function _assetOwner(bytes32 _symbol) internal view returns (uint) { return get(store, assetOwnerIdStorage, _symbol); } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// /// @return success. function issueAsset( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber ) public returns (uint) { return issueAssetWithInitialReceiver(_symbol, _value, _name, _description, _baseUnit, _isReissuable, _blockNumber, msg.sender); } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// @param _account address where issued balance will be held /// /// @return success. function issueAssetWithInitialReceiver( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account ) public onlyOneOfContractOwners returns (uint) { // Should have positive value if supply is going to be fixed. if (_value == 0 && !_isReissuable) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE); } // Should not be issued yet. if (isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED); } uint holderId = _createHolderId(_account); uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender); add(store, symbolsStorage, _symbol); set(store, assetOwnerIdStorage, _symbol, creatorId); set(store, assetTotalSupply, _symbol, _value); set(store, assetName, _symbol, _name); set(store, assetDescription, _symbol, _description); set(store, assetIsReissuable, _symbol, _isReissuable); set(store, assetBaseUnit, _symbol, _baseUnit); set(store, assetWalletBalance, _symbol, holderId, _value); set(store, assetBlockNumber, _symbol, _blockNumber); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _address(holderId)); return OK; } /// @notice Issues additional asset tokens if the asset have dynamic supply. /// /// Tokens issued with this call go straight to asset owner. /// Can only be called by designated asset manager only. /// Inherits all modifiers from reissueAssetToRecepient' function. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// /// @return success. function reissueAsset(bytes32 _symbol, uint _value) public returns (uint) { return reissueAssetToRecepient(_symbol, _value, msg.sender); } /// @notice Issues additional asset tokens `_symbol` if the asset have dynamic supply /// and sends them to recepient address `_to`. /// /// Can only be called by designated asset manager only. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// @param _to recepient address; instead of caller issued amount will be sent to this address /// /// @return success. function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public onlyDesignatedManager(_symbol) onlyAfterBlock(_symbol) returns (uint) { return _reissueAsset(_symbol, _value, _to); } function _reissueAsset(bytes32 _symbol, uint _value, address _to) private returns (uint) { require(_to != 0x0, "CHRONOBANK_PLATFORM_INVALID_RECEPIENT_ADDRESS"); TransactionContext memory txContext; txContext.to = _to; // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have dynamic supply. if (!isReissuable(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET); } uint _totalSupply = totalSupply(_symbol); // Resulting total supply should not overflow. if (_totalSupply + _value < _totalSupply) { return _emitErrorCode(CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW); } txContext.toHolderId = _createHolderId(_to); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); set(store, assetWalletBalance, _symbol, txContext.toHolderId, txContext.balanceTo.add(_value)); set(store, assetTotalSupply, _symbol, _totalSupply.add(_value)); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _to); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAsset(bytes32 _symbol, uint _value) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevoke(_symbol, _value, txContext.from); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevokeExternal(_symbol, _value, txContext.from, _externalReference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _revokeAsset(bytes32 _symbol, uint _value, TransactionContext memory txContext) private returns (uint) { // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough tokens. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS); } txContext.balanceFrom = txContext.balanceFrom.sub(_value); set(store, assetWalletBalance, _symbol, txContext.fromHolderId, txContext.balanceFrom); set(store, assetTotalSupply, _symbol, totalSupply(_symbol).sub(_value)); return OK; } /// @notice Passes asset ownership to specified address. /// /// Only ownership is changed, balances are not touched. /// Can only be called by asset owner. /// /// @param _symbol asset symbol. /// @param _newOwner address to become a new owner. /// /// @return success. function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) { if (_newOwner == 0x0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_NEW_OWNER); } uint newOwnerId = _createHolderId(_newOwner); uint assetOwner = _assetOwner(_symbol); // Should pass ownership to another holder. if (assetOwner == newOwnerId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } address oldOwner = _address(assetOwner); set(store, assetOwnerIdStorage, _symbol, newOwnerId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitOwnershipChange(oldOwner, _newOwner, _symbol); return OK; } /// @notice Check if specified holder trusts an address with recovery procedure. /// @param _from truster. /// @param _to trustee. /// @return trust existance. function isTrusted(address _from, address _to) public view returns (bool) { return get(store, holdersTrustStorage, getHolderId(_from), _to); } /// @notice Trust an address to perform recovery procedure for the caller. /// @param _to trustee. /// @return success. function trust(address _to) public returns (uint) { uint fromId = _createHolderId(msg.sender); // Should trust to another address. if (fromId == getHolderId(_to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should trust to yet untrusted. if (isTrusted(msg.sender, _to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ALREADY_TRUSTED); } set(store, holdersTrustStorage, fromId, _to, true); return OK; } /// @notice Revoke trust to perform recovery procedure from an address. /// @param _to trustee. /// @return success. function distrust(address _to) public checkTrust(msg.sender, _to) returns (uint) { set(store, holdersTrustStorage, getHolderId(msg.sender), _to, false); return OK; } /// @notice Perform recovery procedure. /// /// This function logic is actually more of an addAccess(uint _holderId, address _to). /// It grants another address access to recovery subject wallets. /// Can only be called by trustee of recovery subject. /// /// @param _from holder address to recover from. /// @param _to address to grant access to. /// /// @return success. function recover(address _from, address _to) public checkTrust(_from, msg.sender) returns (uint errorCode) { // Should recover to previously unused address. if (getHolderId(_to) != 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS); } // We take current holder address because it might not equal _from. // It is possible to recover from any old holder address, but event should have the current one. uint _fromHolderId = getHolderId(_from); address _fromRef = _address(_fromHolderId); set(store, holdersAddressStorage, _fromHolderId, _to); set(store, holderIndexStorage, _to, _fromHolderId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitRecovery(_fromRef, _to, msg.sender); return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Note: to revoke allowance, one needs to set allowance to 0. /// /// @param _value amount to allow. /// @param _symbol asset symbol. /// /// @return success. function _approve( uint _value, bytes32 _symbol, TransactionContext memory txContext ) internal returns (uint) { // Asset should exist. if (!isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (txContext.fromHolderId == txContext.senderHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (!(txContext.allowanceValue == 0 || _value == 0)) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_INVOCATION); } set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, _value); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitApprove(txContext.from, txContext.sender, _symbol, _value); address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitApprove(txContext.from, txContext.sender, _value); } return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Can only be called by asset proxy. /// /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _symbol asset symbol. /// @param _sender approve initiator address. /// /// @return success. function proxyApprove( address _spender, uint _value, bytes32 _symbol, address _sender ) public onlyProxy(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _spender; txContext.senderHolderId = _createHolderId(_spender); txContext.from = _sender; txContext.fromHolderId = _createHolderId(_sender); return _approve(_value, _symbol, txContext); } /// @notice Performs allowance transfer of asset balance between holders wallets. /// /// @dev Can only be called by asset proxy. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender allowance transfer initiator address. /// /// @return success. function proxyTransferFromWithReference( address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _from; txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = getHolderId(_from); txContext.senderHolderId = _to == _sender ? txContext.toHolderId : getHolderId(_sender); return _transfer(_value, _symbol, _reference, txContext); } /// @dev Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint) { return _allowance(getHolderId(_from), getHolderId(_spender), _symbol); } /// @dev Returns asset allowance from one holder to another. /// @param _fromId holder id that allowed spending. /// @param _toId holder id that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function _allowance(uint _fromId, uint _toId, bytes32 _symbol) internal view returns (uint) { return get(store, assetWalletAllowance, _symbol, _fromId, _toId); } function _emitter() private view returns (ChronoBankPlatformEmitter) { return ChronoBankPlatformEmitter(getEventsHistory()); } } // File: contracts/EtherTokenExchange.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetProxyInterface is ChronoBankAssetProxy {} contract EtherTokenExchange { uint constant OK = 1; event LogEtherDeposited(address indexed sender, uint amount); event LogEtherWithdrawn(address indexed sender, uint amount); ERC20Interface private token; uint private reentrancyFallbackGuard = 1; constructor(address _token) public { token = ERC20Interface(_token); } function getToken() public view returns (address) { return token; } function deposit() external payable { _deposit(msg.sender, msg.value); } function withdraw(uint _amount) external { require(token.allowance(msg.sender, address(this)) >= _amount, "ETHER_TOKEN_EXCHANGE_NO_APPROVE_PROVIDED"); uint _guardState = reentrancyFallbackGuard; require(token.transferFrom(msg.sender, address(this), _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FROM_FAILED"); if (reentrancyFallbackGuard == _guardState) { _withdraw(msg.sender, _amount); } } function tokenFallback(address _from, uint _value, bytes) external { _incrementGuard(); if (msg.sender == address(token)) { _withdraw(_from, _value); return; } ChronoBankAssetProxyInterface _proxy = ChronoBankAssetProxyInterface(address(token)); address _versionFor = _proxy.getVersionFor(_from); if (!(msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender)) ) { revert("ETHER_TOKEN_EXCHANGE_INVALID_TOKEN"); } _withdraw(_from, _value); } function () external payable { revert("ETHER_TOKEN_EXCHANGE_USE_DEPOSIT_INSTEAD"); } /* PRIVATE */ function _deposit(address _to, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.reissueAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_ISSUE_FAILURE"); require(_token.transfer(_to, _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FAILURE"); emit LogEtherDeposited(_to, _amount); } function _withdraw(address _from, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.revokeAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_REVOKE_FAILURE"); _from.transfer(_amount); emit LogEtherWithdrawn(_from, _amount); } function _incrementGuard() public { reentrancyFallbackGuard += 1; } }
@dev Current asset implementation contract address.
address latestVersion;
1,048,912
[ 1, 3935, 3310, 4471, 6835, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 4891, 1444, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ChainlinkConversionPath.sol"; import "./interfaces/ERC20FeeProxy.sol"; /** * @title Erc20ConversionProxy * @notice This contract convert from chainlink then swaps ERC20 tokens * before paying a request thanks to a conversion payment proxy */ contract Erc20ConversionProxy { address public paymentProxy; ChainlinkConversionPath public chainlinkConversionPath; constructor(address _paymentProxyAddress, address _chainlinkConversionPathAddress) { paymentProxy = _paymentProxyAddress; chainlinkConversionPath = ChainlinkConversionPath(_chainlinkConversionPathAddress); } // Event to declare a conversion with a reference event TransferWithConversionAndReference( uint256 amount, address currency, bytes indexed paymentReference, uint256 feeAmount, uint256 maxRateTimespan ); // Event to declare a transfer with a reference event TransferWithReferenceAndFee( address tokenAddress, address to, uint256 amount, bytes indexed paymentReference, uint256 feeAmount, address feeAddress ); /** * @notice Performs an ERC20 token transfer with a reference computing the payment amount based on the request amount * @param _to Transfer recipient of the payement * @param _requestAmount Request amount * @param _path Conversion path * @param _paymentReference Reference of the payment related * @param _feeAmount The amount of the payment fee * @param _feeAddress The fee recipient * @param _maxToSpend Amount max that we can spend on the behalf of the user * @param _maxRateTimespan Max time span with the oldestrate, ignored if zero */ function transferFromWithReferenceAndFee( address _to, uint256 _requestAmount, address[] calldata _path, bytes calldata _paymentReference, uint256 _feeAmount, address _feeAddress, uint256 _maxToSpend, uint256 _maxRateTimespan ) external { (uint256 amountToPay, uint256 amountToPayInFees) = getConversions( _path, _requestAmount, _feeAmount, _maxRateTimespan); require( amountToPay + amountToPayInFees <= _maxToSpend, "Amount to pay is over the user limit" ); // Pay the request and fees (bool status, ) = paymentProxy.delegatecall( abi.encodeWithSignature( "transferFromWithReferenceAndFee(address,address,uint256,bytes,uint256,address)", // payment currency _path[_path.length - 1], _to, amountToPay, _paymentReference, amountToPayInFees, _feeAddress ) ); require(status, "transferFromWithReferenceAndFee failed"); // Event to declare a transfer with a reference emit TransferWithConversionAndReference( _requestAmount, // request currency _path[0], _paymentReference, _feeAmount, _maxRateTimespan ); } function getConversions( address[] memory _path, uint256 _requestAmount, uint256 _feeAmount, uint256 _maxRateTimespan ) internal view returns (uint256 amountToPay, uint256 amountToPayInFees) { (uint256 rate, uint256 oldestTimestampRate, uint256 decimals) = chainlinkConversionPath.getRate(_path); // Check rate timespan require( _maxRateTimespan == 0 || block.timestamp - oldestTimestampRate <= _maxRateTimespan, "aggregator rate is outdated" ); // Get the amount to pay in the crypto currency chosen amountToPay = (_requestAmount * rate) / decimals; amountToPayInFees = (_feeAmount * rate) /decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./legacy_openzeppelin/contracts/access/roles/WhitelistAdminRole.sol"; interface ERC20fraction { function decimals() external view returns (uint8); } interface AggregatorFraction { function decimals() external view returns (uint8); function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } /** * @title ChainlinkConversionPath * * @notice ChainlinkConversionPath is a contract computing currency conversion rates based on Chainlink aggretators */ contract ChainlinkConversionPath is WhitelistAdminRole { uint constant DECIMALS = 1e18; // Mapping of Chainlink aggregators (input currency => output currency => contract address) // input & output currencies are the addresses of the ERC20 contracts OR the sha3("currency code") mapping(address => mapping(address => address)) public allAggregators; // declare a new aggregator event AggregatorUpdated(address _input, address _output, address _aggregator); /** * @notice Update an aggregator * @param _input address representing the input currency * @param _output address representing the output currency * @param _aggregator address of the aggregator contract */ function updateAggregator(address _input, address _output, address _aggregator) external onlyWhitelistAdmin { allAggregators[_input][_output] = _aggregator; emit AggregatorUpdated(_input, _output, _aggregator); } /** * @notice Update a list of aggregators * @param _inputs list of addresses representing the input currencies * @param _outputs list of addresses representing the output currencies * @param _aggregators list of addresses of the aggregator contracts */ function updateAggregatorsList( address[] calldata _inputs, address[] calldata _outputs, address[] calldata _aggregators ) external onlyWhitelistAdmin { require(_inputs.length == _outputs.length, "arrays must have the same length"); require(_inputs.length == _aggregators.length, "arrays must have the same length"); // For every conversions of the path for (uint i; i < _inputs.length; i++) { allAggregators[_inputs[i]][_outputs[i]] = _aggregators[i]; emit AggregatorUpdated(_inputs[i], _outputs[i], _aggregators[i]); } } /** * @notice Computes the conversion of an amount through a list of intermediate conversions * @param _amountIn Amount to convert * @param _path List of addresses representing the currencies for the intermediate conversions * @return result The result after all the conversions * @return oldestRateTimestamp The oldest timestamp of the path */ function getConversion( uint256 _amountIn, address[] calldata _path ) external view returns (uint256 result, uint256 oldestRateTimestamp) { (uint256 rate, uint256 timestamp, uint256 decimals) = getRate(_path); // initialize the result result = (_amountIn * rate) / decimals; oldestRateTimestamp = timestamp; } /** * @notice Computes the conversion rate from a list of currencies * @param _path List of addresses representing the currencies for the conversions * @return rate The rate * @return oldestRateTimestamp The oldest timestamp of the path * @return decimals of the conversion rate */ function getRate( address[] memory _path ) public view returns (uint256 rate, uint256 oldestRateTimestamp, uint256 decimals) { // initialize the result with 18 decimals (for more precision) rate = DECIMALS; decimals = DECIMALS; oldestRateTimestamp = block.timestamp; // For every conversion of the path for (uint i; i < _path.length - 1; i++) { ( AggregatorFraction aggregator, bool reverseAggregator, uint256 decimalsInput, uint256 decimalsOutput ) = getAggregatorAndDecimals(_path[i], _path[i + 1]); // store the latest timestamp of the path uint256 currentTimestamp = aggregator.latestTimestamp(); if (currentTimestamp < oldestRateTimestamp) { oldestRateTimestamp = currentTimestamp; } // get the rate of the current step uint256 currentRate = uint256(aggregator.latestAnswer()); // get the number of decimals of the current rate uint256 decimalsAggregator = uint256(aggregator.decimals()); // mul with the difference of decimals before the current rate computation (for more precision) if (decimalsAggregator > decimalsInput) { rate = rate * (10**(decimalsAggregator-decimalsInput)); } if (decimalsAggregator < decimalsOutput) { rate = rate * (10**(decimalsOutput-decimalsAggregator)); } // Apply the current rate (if path uses an aggregator in the reverse way, div instead of mul) if (reverseAggregator) { rate = rate * (10**decimalsAggregator) / currentRate; } else { rate = rate * currentRate / (10**decimalsAggregator); } // div with the difference of decimals AFTER the current rate computation (for more precision) if (decimalsAggregator < decimalsInput) { rate = rate / (10**(decimalsInput-decimalsAggregator)); } if (decimalsAggregator > decimalsOutput) { rate = rate / (10**(decimalsAggregator-decimalsOutput)); } } } /** * @notice Gets aggregators and decimals of two currencies * @param _input input Address * @param _output output Address * @return aggregator to get the rate between the two currencies * @return reverseAggregator true if the aggregator returned give the rate from _output to _input * @return decimalsInput decimals of _input * @return decimalsOutput decimals of _output */ function getAggregatorAndDecimals(address _input, address _output) private view returns (AggregatorFraction aggregator, bool reverseAggregator, uint256 decimalsInput, uint256 decimalsOutput) { // Try to get the right aggregator for the conversion aggregator = AggregatorFraction(allAggregators[_input][_output]); reverseAggregator = false; // if no aggregator found we try to find an aggregator in the reverse way if (address(aggregator) == address(0x00)) { aggregator = AggregatorFraction(allAggregators[_output][_input]); reverseAggregator = true; } require(address(aggregator) != address(0x00), "No aggregator found"); // get the decimals for the two currencies decimalsInput = getDecimals(_input); decimalsOutput = getDecimals(_output); } /** * @notice Gets decimals from an address currency * @param _addr address to check * @return decimals number of decimals */ function getDecimals(address _addr) private view returns (uint256 decimals) { // by default we assume it is FIAT so 8 decimals decimals = 8; // if address is the hash of the ETH currency if (_addr == address(0xF5AF88e117747e87fC5929F2ff87221B1447652E)) { decimals = 18; } else if (isContract(_addr)) { // otherwise, we get the decimals from the erc20 directly decimals = ERC20fraction(_addr).decimals(); } } /** * @notice Checks if an address is a contract * @param _addr Address to check * @return true if the address hosts a contract, false otherwise */ function isContract(address _addr) private view returns (bool) { uint32 size; // solium-disable security/no-inline-assembly assembly { size := extcodesize(_addr) } return (size > 0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20FeeProxy { event TransferWithReferenceAndFee( address tokenAddress, address to, uint256 amount, bytes indexed paymentReference, uint256 feeAmount, address feeAddress ); function transferFromWithReferenceAndFee( address _tokenAddress, address _to, uint256 _amount, bytes calldata _paymentReference, uint256 _feeAmount, address _feeAddress ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/Context.sol'; import "../Roles.sol"; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ abstract contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // 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; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } }
* @notice Computes the conversion of an amount through a list of intermediate conversions @param _amountIn Amount to convert @param _path List of addresses representing the currencies for the intermediate conversions @return result The result after all the conversions @return oldestRateTimestamp The oldest timestamp of the path/ initialize the result
function getConversion( uint256 _amountIn, address[] calldata _path ) external view returns (uint256 result, uint256 oldestRateTimestamp) { (uint256 rate, uint256 timestamp, uint256 decimals) = getRate(_path); result = (_amountIn * rate) / decimals; oldestRateTimestamp = timestamp; }
1,173,787
[ 1, 10743, 326, 4105, 434, 392, 3844, 3059, 279, 666, 434, 12110, 22586, 225, 389, 8949, 382, 16811, 358, 1765, 225, 389, 803, 987, 434, 6138, 5123, 326, 19239, 364, 326, 12110, 22586, 327, 563, 1021, 563, 1839, 777, 326, 22586, 327, 17067, 4727, 4921, 1021, 17067, 2858, 434, 326, 589, 19, 4046, 326, 563, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 336, 6814, 12, 203, 565, 2254, 5034, 389, 8949, 382, 16, 203, 565, 1758, 8526, 745, 892, 389, 803, 203, 225, 262, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 563, 16, 2254, 5034, 17067, 4727, 4921, 13, 203, 225, 288, 203, 565, 261, 11890, 5034, 4993, 16, 2254, 5034, 2858, 16, 2254, 5034, 15105, 13, 273, 4170, 340, 24899, 803, 1769, 203, 203, 565, 563, 273, 261, 67, 8949, 382, 380, 4993, 13, 342, 15105, 31, 203, 203, 565, 17067, 4727, 4921, 273, 2858, 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 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ACT93636' token contract // // Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187 // Symbol : ACT93636 // Name : ADZbuzz Montrealhousedeals.com Community Token // Total supply: 2000000 // Decimals : 8 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // (c) by Darwin Jayme with ADZbuzz Ltd. UK (adzbuzz.com) 2018. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // 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 = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ADZbuzzCommunityToken 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 ADZbuzzCommunityToken() public { symbol = "ACT93636"; name = "ADZbuzz Montrealhousedeals.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract ADZbuzzCommunityToken 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 ADZbuzzCommunityToken() public { symbol = "ACT93636"; name = "ADZbuzz Montrealhousedeals.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _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); 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] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } 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 { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1,574,146
[ 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, 565, 6835, 11738, 62, 70, 9510, 12136, 13352, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 3639, 533, 1071, 3273, 31, 203, 3639, 533, 1071, 225, 508, 31, 203, 3639, 2254, 28, 1071, 15105, 31, 203, 3639, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 377, 203, 3639, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 377, 203, 377, 203, 3639, 445, 11738, 62, 70, 9510, 12136, 13352, 1345, 1435, 1071, 288, 203, 5411, 3273, 273, 315, 6526, 11180, 4449, 26, 14432, 203, 5411, 508, 273, 315, 1880, 62, 70, 9510, 490, 1580, 7688, 13028, 323, 1031, 18, 832, 16854, 13352, 3155, 14432, 203, 5411, 15105, 273, 1725, 31, 203, 5411, 389, 4963, 3088, 1283, 273, 576, 12648, 9449, 31, 203, 5411, 324, 26488, 63, 20, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 65, 273, 389, 4963, 3088, 1283, 31, 203, 5411, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 16, 389, 4963, 3088, 1283, 1769, 203, 3639, 289, 203, 377, 203, 377, 203, 3639, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 5411, 2 ]
./partial_match/4/0xFD08F9d24c673216663928acb6BF5Ac1c09FEd0C/sources/YVAULTMASTER.sol
Safe yvault transfer function, just in case if rounding error causes pool to not have enough YVAULTs.
function safeYvaultTransfer(address _to, uint256 _amount) internal { uint256 yvaultBal = yvault.balanceOf(address(this)); if (_amount > yvaultBal) { yvault.transfer(_to, yvaultBal); yvault.transfer(_to, _amount); } }
8,687,362
[ 1, 9890, 677, 26983, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 1624, 27722, 2274, 87, 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, 4183, 61, 26983, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 677, 26983, 38, 287, 273, 677, 26983, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 677, 26983, 38, 287, 13, 288, 203, 5411, 677, 26983, 18, 13866, 24899, 869, 16, 677, 26983, 38, 287, 1769, 203, 5411, 677, 26983, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xacD725Cf8906dAD85Fda40a0D621DCE2C1F99563/sources/contracts/LootERC20.sol
@notice Allows baal to create a snapshot
function snapshot() external onlyOwner { _snapshot(); }
4,879,638
[ 1, 19132, 9846, 287, 358, 752, 279, 4439, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4439, 1435, 3903, 1338, 5541, 288, 203, 3639, 389, 11171, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x759f001b3fDe502537901a1e85E8e01333657864/sources/test.sol
/ validate input special case for 0 sell amount special case for selling the entire supply special case if the weight = 100%
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view override returns (uint256) { require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); if (_sellAmount == 0) return 0; if (_sellAmount == _supply) return _connectorBalance; 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; } 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
9,475,074
[ 1, 19, 1954, 810, 4582, 648, 364, 374, 357, 80, 3844, 4582, 648, 364, 357, 2456, 326, 7278, 14467, 4582, 648, 309, 326, 3119, 273, 2130, 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 ]
[ 1, 1, 1, 1, 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, 4604, 30746, 990, 12, 11890, 5034, 389, 2859, 1283, 16, 2254, 5034, 389, 23159, 13937, 16, 2254, 1578, 389, 23159, 6544, 16, 2254, 5034, 389, 87, 1165, 6275, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 24899, 2859, 1283, 405, 374, 597, 389, 23159, 13937, 405, 374, 597, 389, 23159, 6544, 405, 374, 597, 389, 23159, 6544, 1648, 4552, 67, 29988, 597, 389, 87, 1165, 6275, 1648, 389, 2859, 1283, 1769, 203, 203, 3639, 309, 261, 67, 87, 1165, 6275, 422, 374, 13, 203, 5411, 327, 374, 31, 203, 203, 3639, 309, 261, 67, 87, 1165, 6275, 422, 389, 2859, 1283, 13, 203, 5411, 327, 389, 23159, 13937, 31, 203, 203, 3639, 309, 261, 67, 23159, 6544, 422, 4552, 67, 29988, 13, 203, 5411, 327, 389, 23159, 13937, 18, 16411, 24899, 87, 1165, 6275, 13, 342, 389, 2859, 1283, 31, 203, 203, 3639, 2254, 5034, 563, 31, 203, 3639, 2254, 28, 6039, 31, 203, 3639, 2254, 5034, 1026, 40, 273, 389, 2859, 1283, 300, 389, 87, 1165, 6275, 31, 203, 3639, 261, 2088, 16, 6039, 13, 273, 7212, 24899, 2859, 1283, 16, 1026, 40, 16, 4552, 67, 29988, 16, 389, 23159, 6544, 1769, 203, 3639, 2254, 5034, 1906, 21, 273, 389, 23159, 13937, 18, 16411, 12, 2088, 1769, 203, 3639, 2254, 5034, 1906, 22, 273, 389, 23159, 13937, 2296, 6039, 31, 203, 3639, 327, 261, 5814, 21, 300, 1906, 22, 13, 342, 563, 31, 203, 565, 289, 203, 203, 3639, 17264, 326, 327, 364, 279, 4105, 628, 2 ]
./partial_match/1/0x5903cb31b6d62D0C474159E45886c446bfe0eFD6/sources/XGPT.sol
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract XGPT is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("X-GPT", "X-GPT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 20; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 67; uint256 totalSupply = 1_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading(bool enabled) external onlyOwner { if(enabled){ tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } } function enableTrading(bool enabled) external onlyOwner { if(enabled){ tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } } function vanishLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function adjustSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function adjustLimits(uint256 newNumTx, uint256 newNumWallet) external onlyOwner { require( newNumTx >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNumTx * (10**18); require( newNumWallet >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNumWallet * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function adjustFees(uint256 _buyMarketingFee, uint256 _buyLiquidityFee, uint256 _buyDevFee, uint256 _sellMarketingFee, uint256 _sellLiquidityFee, uint256 _sellDevFee) external onlyOwner{ buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 75, "Must keep fees at 75% or less"); sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 75, "Must keep fees at 75% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedMaxTransactionAmount[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / (success, ) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); }
9,225,317
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1139, 43, 1856, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 12396, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 203, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 638, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 2 ]
pragma solidity 0.5.11; /** * @title OUSD Vault Contract * @notice The Vault contract stores assets. On a deposit, OUSD will be minted and sent to the depositor. On a withdrawal, OUSD will be burned and assets will be sent to the withdrawer. The Vault accepts deposits of interest form yield bearing strategies which will modify the supply of OUSD. * @author Origin Protocol Inc */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract Governable { // Storage position of the owner and pendingOwner of the contract bytes32 private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a; //keccak256("OUSD.governor"); bytes32 private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db; //keccak256("OUSD.pending.governor"); event PendingGovernorshipTransfer( address indexed previousGovernor, address indexed newGovernor ); event GovernorshipTransferred( address indexed previousGovernor, address indexed newGovernor ); /** * @dev Initializes the contract setting the deployer as the initial Governor. */ constructor() internal { _setGovernor(msg.sender); emit GovernorshipTransferred(address(0), _governor()); } /** * @dev Returns the address of the current Governor. */ function governor() public view returns (address) { return _governor(); } function _governor() internal view returns (address governorOut) { bytes32 position = governorPosition; assembly { governorOut := sload(position) } } function _pendingGovernor() internal view returns (address pendingGovernor) { bytes32 position = pendingGovernorPosition; assembly { pendingGovernor := sload(position) } } /** * @dev Throws if called by any account other than the Governor. */ modifier onlyGovernor() { require(isGovernor(), "Caller is not the Governor"); _; } /** * @dev Returns true if the caller is the current Governor. */ function isGovernor() public view returns (bool) { return msg.sender == _governor(); } function _setGovernor(address newGovernor) internal { bytes32 position = governorPosition; assembly { sstore(position, newGovernor) } } function _setPendingGovernor(address newGovernor) internal { bytes32 position = pendingGovernorPosition; assembly { sstore(position, newGovernor) } } /** * @dev Transfers Governance of the contract to a new account (`newGovernor`). * Can only be called by the current Governor. Must be claimed for this to complete * @param _newGovernor Address of the new Governor */ function transferGovernance(address _newGovernor) external onlyGovernor { _setPendingGovernor(_newGovernor); emit PendingGovernorshipTransfer(_governor(), _newGovernor); } /** * @dev Claim Governance of the contract to a new account (`newGovernor`). * Can only be called by the new Governor. */ function claimGovernance() external { require( msg.sender == _pendingGovernor(), "Only the pending Governor can complete the claim" ); _changeGovernor(msg.sender); } /** * @dev Change Governance of the contract to a new account (`newGovernor`). * @param _newGovernor Address of the new Governor */ function _changeGovernor(address _newGovernor) internal { require(_newGovernor != address(0), "New Governor is address(0)"); emit GovernorshipTransferred(_governor(), _newGovernor); _setGovernor(_newGovernor); } } interface IBasicToken { function symbol() external view returns (string memory); function decimals() external view returns (uint8); } interface IMinMaxOracle { //Assuming 8 decimals function priceMin(string calldata symbol) external returns (uint256); function priceMax(string calldata symbol) external returns (uint256); } interface IViewMinMaxOracle { function priceMin(string calldata symbol) external view returns (uint256); function priceMax(string calldata symbol) external view returns (uint256); } interface IStrategy { /** * @dev Deposit the given asset to Lending platform. * @param _asset asset address * @param _amount Amount to deposit */ function deposit(address _asset, uint256 _amount) external returns (uint256 amountDeposited); /** * @dev Withdraw given asset from Lending platform */ function withdraw( address _recipient, address _asset, uint256 _amount ) external returns (uint256 amountWithdrawn); /** * @dev Returns the current balance of the given asset. */ function checkBalance(address _asset) external view returns (uint256 balance); /** * @dev Returns bool indicating whether strategy supports asset. */ function supportsAsset(address _asset) external view returns (bool); /** * @dev Liquidate all assets in strategy and return them to Vault. */ function liquidate() external; /** * @dev Get the APR for the Strategy. */ function getAPR() external view returns (uint256); /** * @dev Collect reward tokens from the Strategy. */ function collectRewardToken() external; } library Helpers { /** * @notice Fetch the `symbol()` from an ERC20 token * @dev Grabs the `symbol()` from a contract * @param _token Address of the ERC20 token * @return string Symbol of the ERC20 token */ function getSymbol(address _token) internal view returns (string memory) { string memory symbol = IBasicToken(_token).symbol(); return symbol; } /** * @notice Fetch the `decimals()` from an ERC20 token * @dev Grabs the `decimals()` from a contract and fails if * the decimal value does not live within a certain range * @param _token Address of the ERC20 token * @return uint256 Decimals of the ERC20 token */ function getDecimals(address _token) internal view returns (uint256) { uint256 decimals = IBasicToken(_token).decimals(); require( decimals >= 4 && decimals <= 18, "Token must have sufficient decimal places" ); return decimals; } } contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract InitializableToken is ERC20, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract OUSD is Initializable, InitializableToken, Governable { using SafeMath for uint256; using StableMath for uint256; event TotalSupplyUpdated( uint256 totalSupply, uint256 totalCredits, uint256 creditsPerToken ); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private totalCredits; // Exchange rate between internal credits and OUSD uint256 private creditsPerToken; mapping(address => uint256) private _creditBalances; // Allowances denominated in OUSD mapping(address => mapping(address => uint256)) private _allowances; address public vaultAddress = address(0); function initialize( string calldata _nameArg, string calldata _symbolArg, address _vaultAddress ) external onlyGovernor initializer { InitializableToken._initialize(_nameArg, _symbolArg); _totalSupply = 0; totalCredits = 0; creditsPerToken = 1e18; vaultAddress = _vaultAddress; } /** * @dev Verifies that the caller is the Savings Manager contract */ modifier onlyVault() { require(vaultAddress == msg.sender, "Caller is not the Vault"); _; } /** * @return The total supply of OUSD. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _account The address to query the balance of. * @return A unit256 representing the _amount of base units owned by the * specified address. */ function balanceOf(address _account) public view returns (uint256) { if (creditsPerToken == 0) return 0; return _creditBalances[_account].divPrecisely(creditsPerToken); } /** * @dev Gets the credits balance of the specified address. * @param _account The address to query the balance of. * @return A uint256 representing the _amount of base units owned by the * specified address. */ function creditsBalanceOf(address _account) public view returns (uint256) { return _creditBalances[_account]; } /** * @dev Transfer tokens to a specified address. * @param _to the address to transfer to. * @param _value the _amount to be transferred. * @return true on success. */ function transfer(address _to, uint256 _value) public returns (bool) { uint256 creditValue = _removeCredits(msg.sender, _value); _creditBalances[_to] = _creditBalances[_to].add(creditValue); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another. * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value The _amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub( _value ); uint256 creditValue = _removeCredits(_from, _value); _creditBalances[_to] = _creditBalances[_to].add(creditValue); emit Transfer(_from, _to, _value); return true; } /** * @dev Function to check the _amount of tokens that an owner has allowed to a _spender. * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return The number of tokens still available for the _spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return _allowances[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified _amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param _spender The address which will spend the funds. * @param _value The _amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { _allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the _amount of tokens that an owner has allowed to a _spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param _spender The address which will spend the funds. * @param _addedValue The _amount of tokens to increase the allowance by. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender] .add(_addedValue); emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Decrease the _amount of tokens that an owner has allowed to a _spender. * @param _spender The address which will spend the funds. * @param _subtractedValue The _amount of tokens to decrease the allowance by. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = _allowances[msg.sender][_spender]; if (_subtractedValue >= oldValue) { _allowances[msg.sender][_spender] = 0; } else { _allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @notice Mints new tokens, increasing totalSupply. */ function mint(address _account, uint256 _amount) external onlyVault { return _mint(_account, _amount); } /** * @dev Creates `_amount` tokens and assigns them to `_account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address _account, uint256 _amount) internal { require(_account != address(0), "Mint to the zero address"); _totalSupply = _totalSupply.add(_amount); uint256 creditAmount = _amount.mulTruncate(creditsPerToken); _creditBalances[_account] = _creditBalances[_account].add(creditAmount); totalCredits = totalCredits.add(creditAmount); emit Transfer(address(0), _account, _amount); } /** * @notice Burns tokens, decreasing totalSupply. */ function burn(address account, uint256 amount) external onlyVault { return _burn(account, amount); } /** * @dev Destroys `_amount` tokens from `_account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `_account` cannot be the zero address. * - `_account` must have at least `_amount` tokens. */ function _burn(address _account, uint256 _amount) internal { require(_account != address(0), "Burn from the zero address"); _totalSupply = _totalSupply.sub(_amount); uint256 creditAmount = _removeCredits(_account, _amount); totalCredits = totalCredits.sub(creditAmount); emit Transfer(_account, address(0), _amount); } /** * @dev Removes credits from a credit balance and burns rounding errors. * @param _account Account to remove credits from * @param _amount Amount in OUSD which will be converted to credits and * removed */ function _removeCredits(address _account, uint256 _amount) internal returns (uint256 creditAmount) { creditAmount = _amount.mulTruncate(creditsPerToken); uint256 currentCredits = _creditBalances[_account]; if ( currentCredits == creditAmount || currentCredits - 1 == creditAmount ) { _creditBalances[_account] = 0; } else if (currentCredits > creditAmount) { _creditBalances[_account] = currentCredits - creditAmount; } else { revert("Remove exceeds balance"); } } /** * @dev Modify the supply without minting new tokens. This uses a change in * the exchange rate between "credits" and OUSD tokens to change balances. * @param _newTotalSupply New total supply of OUSD. * @return uint256 representing the new total supply. */ function changeSupply(uint256 _newTotalSupply) external onlyVault returns (uint256) { require(_totalSupply > 0, "Cannot increase 0 supply"); if (_totalSupply == _newTotalSupply) { emit TotalSupplyUpdated( _totalSupply, totalCredits, creditsPerToken ); return _totalSupply; } _totalSupply = _newTotalSupply; if (_totalSupply > MAX_SUPPLY) _totalSupply = MAX_SUPPLY; creditsPerToken = totalCredits.divPrecisely(_totalSupply); emit TotalSupplyUpdated(_totalSupply, totalCredits, creditsPerToken); return _totalSupply; } } library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /*************************************** Helpers ****************************************/ /** * @dev Adjust the scale of an integer * @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17 */ function scaleBy(uint256 x, int8 adjustment) internal pure returns (uint256) { if (adjustment > 0) { x = x.mul(10**uint256(adjustment)); } else if (adjustment < 0) { x = x.div(10**uint256(adjustment * -1)); } return x; } /*************************************** Precise Arithmetic ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } } contract Vault is Initializable, Governable { using SafeMath for uint256; using StableMath for uint256; using SafeMath for int256; using SafeERC20 for IERC20; event AssetSupported(address _asset); event StrategyAdded(address _addr); event StrategyRemoved(address _addr); event Mint(address _addr, uint256 _value); event Redeem(address _addr, uint256 _value); event StrategyWeightsUpdated( address[] _strategyAddresses, uint256[] weights ); event DepositsPaused(); event DepositsUnpaused(); // Assets supported by the Vault, i.e. Stablecoins struct Asset { bool isSupported; } mapping(address => Asset) assets; address[] allAssets; // Strategies supported by the Vault struct Strategy { bool isSupported; uint256 targetWeight; // 18 decimals. 100% = 1e18 } mapping(address => Strategy) strategies; address[] allStrategies; // Address of the Oracle price provider contract address public priceProvider; // Pausing bools bool public rebasePaused = false; bool public depositPaused = true; // Redemption fee in basis points uint256 public redeemFeeBps; // Buffer of assets to keep in Vault to handle (most) withdrawals uint256 public vaultBuffer; // Mints over this amount automatically allocate funds. 18 decimals. uint256 public autoAllocateThreshold; // Mints over this amount automatically rebase. 18 decimals. uint256 public rebaseThreshold; OUSD oUSD; /** * @dev Verifies that the rebasing is not paused. */ modifier whenNotRebasePaused() { require(!rebasePaused, "Rebasing paused"); _; } /*************************************** Configuration ****************************************/ /** * @dev Set address of price provider. * @param _priceProvider Address of price provider */ function setPriceProvider(address _priceProvider) external onlyGovernor { priceProvider = _priceProvider; } /** * @dev Set a fee in basis points to be charged for a redeem. * @param _redeemFeeBps Basis point fee to be charged */ function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor { redeemFeeBps = _redeemFeeBps; } /** * @dev Set a buffer of assets to keep in the Vault to handle most * redemptions without needing to spend gas unwinding assets from a Strategy. * @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18. */ function setVaultBuffer(uint256 _vaultBuffer) external onlyGovernor { vaultBuffer = _vaultBuffer; } /** * @dev Sets the minimum amount of OUSD in a mint to trigger an * automatic allocation of funds afterwords. * @param _threshold OUSD amount with 18 fixed decimals. */ function setAutoAllocateThreshold(uint256 _threshold) external onlyGovernor { autoAllocateThreshold = _threshold; } /** * @dev Set a minimum amount of OUSD in a mint or redeem that triggers a * rebase * @param _threshold OUSD amount with 18 fixed decimals. */ function setRebaseThreshold(uint256 _threshold) external onlyGovernor { rebaseThreshold = _threshold; } /** @dev Add a supported asset to the contract, i.e. one that can be * to mint OUSD. * @param _asset Address of asset */ function supportAsset(address _asset) external onlyGovernor { require(!assets[_asset].isSupported, "Asset already supported"); assets[_asset] = Asset({ isSupported: true }); allAssets.push(_asset); emit AssetSupported(_asset); } /** * @dev Add a strategy to the Vault. * @param _addr Address of the strategy to add * @param _targetWeight Target percentage of asset allocation to strategy */ function addStrategy(address _addr, uint256 _targetWeight) external onlyGovernor { require(!strategies[_addr].isSupported, "Strategy already added"); strategies[_addr] = Strategy({ isSupported: true, targetWeight: _targetWeight }); allStrategies.push(_addr); emit StrategyAdded(_addr); } /** * @dev Remove a strategy from the Vault. Removes all invested assets and * returns them to the Vault. * @param _addr Address of the strategy to remove */ function removeStrategy(address _addr) external onlyGovernor { require(strategies[_addr].isSupported, "Strategy not added"); // Initialize strategyIndex with out of bounds result so function will // revert if no valid index found uint256 strategyIndex = allStrategies.length; for (uint256 i = 0; i < allStrategies.length; i++) { if (allStrategies[i] == _addr) { strategyIndex = i; break; } } assert(strategyIndex < allStrategies.length); allStrategies[strategyIndex] = allStrategies[allStrategies.length - 1]; allStrategies.length--; // Liquidate all assets IStrategy strategy = IStrategy(_addr); strategy.liquidate(); emit StrategyRemoved(_addr); } /** * @notice Set the weights for multiple strategies. * @param _strategyAddresses Array of strategy addresses * @param _weights Array of corresponding weights, with 18 decimals. * For ex. 100%=1e18, 30%=3e17. */ function setStrategyWeights( address[] calldata _strategyAddresses, uint256[] calldata _weights ) external onlyGovernor { require( _strategyAddresses.length == _weights.length, "Parameter length mismatch" ); for (uint256 i = 0; i < _strategyAddresses.length; i++) { strategies[_strategyAddresses[i]].targetWeight = _weights[i]; } emit StrategyWeightsUpdated(_strategyAddresses, _weights); } /*************************************** Core ****************************************/ /** * @dev Deposit a supported asset and mint OUSD. * @param _asset Address of the asset being deposited * @param _amount Amount of the asset being deposited */ function mint(address _asset, uint256 _amount) external { require(!depositPaused, "Deposits are paused"); require(assets[_asset].isSupported, "Asset is not supported"); require(_amount > 0, "Amount must be greater than 0"); uint256[] memory assetPrices; // For now we have to live with the +1 oracle call because we need to // know the priceAdjustedDeposit before we decide wether or not to grab // assets. This will not effect small non-rebase/allocate mints uint256 priceAdjustedDeposit = _amount.mulTruncateScale( IMinMaxOracle(priceProvider) .priceMin(Helpers.getSymbol(_asset)) .scaleBy(int8(10)), // 18-8 because oracles have 8 decimals precision 10**Helpers.getDecimals(_asset) ); if ( (priceAdjustedDeposit > rebaseThreshold && !rebasePaused) || (priceAdjustedDeposit >= autoAllocateThreshold) ) { assetPrices = _getAssetPrices(false); } // Rebase must happen before any transfers occur. if (priceAdjustedDeposit > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } // Transfer the deposited coins to the vault IERC20 asset = IERC20(_asset); asset.safeTransferFrom(msg.sender, address(this), _amount); // Mint matching OUSD oUSD.mint(msg.sender, priceAdjustedDeposit); emit Mint(msg.sender, priceAdjustedDeposit); if (priceAdjustedDeposit >= autoAllocateThreshold) { allocate(assetPrices); } } /** * @dev Mint for multiple assets in the same call. * @param _assets Addresses of assets being deposited * @param _amounts Amount of each asset at the same index in the _assets * to deposit. */ function mintMultiple( address[] calldata _assets, uint256[] calldata _amounts ) external { require(_assets.length == _amounts.length, "Parameter length mismatch"); uint256 priceAdjustedTotal = 0; uint256[] memory assetPrices = _getAssetPrices(false); for (uint256 i = 0; i < allAssets.length; i++) { for (uint256 j = 0; j < _assets.length; j++) { if (_assets[j] == allAssets[i]) { if (_amounts[j] > 0) { uint256 assetDecimals = Helpers.getDecimals( allAssets[i] ); priceAdjustedTotal += _amounts[j].mulTruncateScale( assetPrices[i], 10**assetDecimals ); } } } } // Rebase must happen before any transfers occur. if (priceAdjustedTotal > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } for (uint256 i = 0; i < _assets.length; i++) { IERC20 asset = IERC20(_assets[i]); asset.safeTransferFrom(msg.sender, address(this), _amounts[i]); } oUSD.mint(msg.sender, priceAdjustedTotal); emit Mint(msg.sender, priceAdjustedTotal); if (priceAdjustedTotal >= autoAllocateThreshold) { allocate(assetPrices); } } /** * @dev Withdraw a supported asset and burn OUSD. * @param _amount Amount of OUSD to burn */ function redeem(uint256 _amount) public { uint256[] memory assetPrices = _getAssetPrices(false); if (_amount > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } _redeem(_amount, assetPrices); } function _redeem(uint256 _amount, uint256[] memory assetPrices) internal { require(_amount > 0, "Amount must be greater than 0"); uint256 feeAdjustedAmount; if (redeemFeeBps > 0) { uint256 redeemFee = _amount.mul(redeemFeeBps).div(10000); feeAdjustedAmount = _amount.sub(redeemFee); } else { feeAdjustedAmount = _amount; } // Calculate redemption outputs uint256[] memory outputs = _calculateRedeemOutputs(feeAdjustedAmount); // Send outputs for (uint256 i = 0; i < allAssets.length; i++) { if (outputs[i] == 0) continue; IERC20 asset = IERC20(allAssets[i]); if (asset.balanceOf(address(this)) >= outputs[i]) { // Use Vault funds first if sufficient asset.safeTransfer(msg.sender, outputs[i]); } else { address strategyAddr = _selectWithdrawStrategyAddr( allAssets[i], outputs[i], assetPrices ); if (strategyAddr != address(0)) { // Nothing in Vault, but something in Strategy, send from there IStrategy strategy = IStrategy(strategyAddr); strategy.withdraw(msg.sender, allAssets[i], outputs[i]); } else { // Cant find funds anywhere revert("Liquidity error"); } } } oUSD.burn(msg.sender, _amount); // Until we can prove that we won't affect the prices of our assets // by withdrawing them, this should be here. // It's possible that a strategy was off on its asset total, perhaps // a reward token sold for more or for less than anticipated. if (_amount > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } emit Redeem(msg.sender, _amount); } /** * @notice Withdraw a supported asset and burn all OUSD. */ function redeemAll() external { uint256[] memory assetPrices = _getAssetPrices(false); //unfortunately we have to do balanceOf twice if (oUSD.balanceOf(msg.sender) > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } _redeem(oUSD.balanceOf(msg.sender), assetPrices); } /** * @notice Allocate unallocated funds on Vault to strategies. * @dev Allocate unallocated funds on Vault to strategies. **/ function allocate() public { uint256[] memory assetPrices = _getAssetPrices(false); allocate(assetPrices); } /** * @notice Allocate unallocated funds on Vault to strategies. * @dev Allocate unallocated funds on Vault to strategies. **/ function allocate(uint256[] memory assetPrices) internal { uint256 vaultValue = _totalValueInVault(assetPrices); // Nothing in vault to allocate if (vaultValue == 0) return; uint256 strategiesValue = _totalValueInStrategies(assetPrices); // We have a method that does the same as this, gas optimisation uint256 totalValue = vaultValue + strategiesValue; // We want to maintain a buffer on the Vault so calculate a percentage // modifier to multiply each amount being allocated by to enforce the // vault buffer uint256 vaultBufferModifier; if (strategiesValue == 0) { // Nothing in Strategies, allocate 100% minus the vault buffer to // strategies vaultBufferModifier = 1e18 - vaultBuffer; } else { vaultBufferModifier = vaultBuffer.mul(totalValue).div(vaultValue); if (1e18 > vaultBufferModifier) { // E.g. 1e18 - (1e17 * 10e18)/5e18 = 8e17 // (5e18 * 8e17) / 1e18 = 4e18 allocated from Vault vaultBufferModifier = 1e18 - vaultBufferModifier; } else { // We need to let the buffer fill return; } } if (vaultBufferModifier == 0) return; // Iterate over all assets in the Vault and allocate the the appropriate // strategy for (uint256 i = 0; i < allAssets.length; i++) { IERC20 asset = IERC20(allAssets[i]); uint256 assetBalance = asset.balanceOf(address(this)); // No balance, nothing to do here if (assetBalance == 0) continue; // Multiply the balance by the vault buffer modifier and truncate // to the scale of the asset decimals uint256 allocateAmount = assetBalance.mulTruncate( vaultBufferModifier ); // Get the target Strategy to maintain weightings address depositStrategyAddr = _selectDepositStrategyAddr( address(asset), assetPrices ); if (depositStrategyAddr != address(0) && allocateAmount > 0) { IStrategy strategy = IStrategy(depositStrategyAddr); // Transfer asset to Strategy and call deposit method to // mint or take required action asset.safeTransfer(address(strategy), allocateAmount); strategy.deposit(address(asset), allocateAmount); } } } /** * @dev Calculate the total value of assets held by the Vault and all * strategies and update the supply of oUSD */ function rebase() public whenNotRebasePaused returns (uint256) { uint256[] memory assetPrices = _getAssetPrices(false); rebase(assetPrices); } /** * @dev Calculate the total value of assets held by the Vault and all * strategies and update the supply of oUSD */ function rebase(uint256[] memory assetPrices) internal whenNotRebasePaused returns (uint256) { if (oUSD.totalSupply() == 0) return 0; return oUSD.changeSupply(_totalValue(assetPrices)); } /** * @dev Determine the total value of assets held by the vault and its * strategies. * @return uint256 value Total value in USD (1e18) */ function totalValue() external returns (uint256 value) { uint256[] memory assetPrices = _getAssetPrices(false); value = _totalValue(assetPrices); } /** * @dev Internal Calculate the total value of the assets held by the * vault and its strategies. * @return uint256 value Total value in USD (1e18) */ function _totalValue(uint256[] memory assetPrices) internal view returns (uint256 value) { return _totalValueInVault(assetPrices) + _totalValueInStrategies(assetPrices); } /** * @dev Internal to calculate total value of all assets held in Vault. * @return uint256 Total value in ETH (1e18) */ function _totalValueInVault(uint256[] memory assetPrices) internal view returns (uint256 value) { value = 0; for (uint256 y = 0; y < allAssets.length; y++) { IERC20 asset = IERC20(allAssets[y]); uint256 assetDecimals = Helpers.getDecimals(allAssets[y]); uint256 balance = asset.balanceOf(address(this)); if (balance > 0) { value += balance.mulTruncateScale( assetPrices[y], 10**assetDecimals ); } } } /** * @dev Internal to calculate total value of all assets held in Strategies. * @return uint256 Total value in ETH (1e18) */ function _totalValueInStrategies(uint256[] memory assetPrices) internal view returns (uint256 value) { value = 0; for (uint256 i = 0; i < allStrategies.length; i++) { value += _totalValueInStrategy(allStrategies[i], assetPrices); } } /** * @dev Internal to calculate total value of all assets held by strategy. * @param _strategyAddr Address of the strategy * @return uint256 Total value in ETH (1e18) */ function _totalValueInStrategy( address _strategyAddr, uint256[] memory assetPrices ) internal view returns (uint256 value) { value = 0; IStrategy strategy = IStrategy(_strategyAddr); for (uint256 y = 0; y < allAssets.length; y++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[y]); if (strategy.supportsAsset(allAssets[y])) { uint256 balance = strategy.checkBalance(allAssets[y]); if (balance > 0) { value += balance.mulTruncateScale( assetPrices[y], 10**assetDecimals ); } } } } /** * @dev Calculate difference in percent of asset allocation for a strategy. * @param _strategyAddr Address of the strategy * @return int256 Difference between current and target. 18 decimals. For ex. 10%=1e17. */ function _strategyWeightDifference( address _strategyAddr, uint256[] memory assetPrices ) internal view returns (int256 difference) { difference = int256(strategies[_strategyAddr].targetWeight) - int256( _totalValueInStrategy(_strategyAddr, assetPrices).divPrecisely( _totalValue(assetPrices) ) ); } /** * @dev Select a strategy for allocating an asset to. * @param _asset Address of asset * @return address Address of the target strategy */ function _selectDepositStrategyAddr( address _asset, uint256[] memory assetPrices ) internal view returns (address depositStrategyAddr) { depositStrategyAddr = address(0); int256 maxDifference = 0; for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.supportsAsset(_asset)) { int256 diff = _strategyWeightDifference( allStrategies[i], assetPrices ); if (diff >= maxDifference) { maxDifference = diff; depositStrategyAddr = allStrategies[i]; } } } } /** * @dev Select a strategy for withdrawing an asset from. * @param _asset Address of asset * @return address Address of the target strategy for withdrawal */ function _selectWithdrawStrategyAddr( address _asset, uint256 _amount, uint256[] memory assetPrices ) internal view returns (address withdrawStrategyAddr) { withdrawStrategyAddr = address(0); int256 minDifference = 1e18; for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if ( strategy.supportsAsset(_asset) && strategy.checkBalance(_asset) > _amount ) { int256 diff = _strategyWeightDifference( allStrategies[i], assetPrices ); if (diff <= minDifference) { minDifference = diff; withdrawStrategyAddr = allStrategies[i]; } } } } /** * @notice Get the balance of an asset held in Vault and all strategies. * @param _asset Address of asset * @return uint256 Balance of asset in decimals of asset */ function checkBalance(address _asset) external view returns (uint256) { return _checkBalance(_asset); } /** * @notice Get the balance of an asset held in Vault and all strategies. * @param _asset Address of asset * @return uint256 Balance of asset in decimals of asset */ function _checkBalance(address _asset) internal view returns (uint256 balance) { IERC20 asset = IERC20(_asset); balance = asset.balanceOf(address(this)); for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.supportsAsset(_asset)) { balance += strategy.checkBalance(_asset); } } } /** * @notice Get the balance of all assets held in Vault and all strategies. * @return uint256 Balance of all assets (1e18) */ function _checkBalance() internal view returns (uint256 balance) { balance = 0; for (uint256 i = 0; i < allAssets.length; i++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[i]); balance += _checkBalance(allAssets[i]).scaleBy( int8(18 - assetDecimals) ); } } /** * @notice Calculate the outputs for a redeem function, i.e. the mix of * coins that will be returned */ function calculateRedeemOutputs(uint256 _amount) external returns (uint256[] memory) { return _calculateRedeemOutputs(_amount); } /** * @notice Calculate the outputs for a redeem function, i.e. the mix of * coins that will be returned. * @return Array of amounts respective to the supported assets */ function _calculateRedeemOutputs(uint256 _amount) internal returns (uint256[] memory outputs) { uint256[] memory assetPrices = _getAssetPrices(true); uint256 totalBalance = _checkBalance(); uint256 totalOutputValue = 0; // Running total of USD value of assets uint256 assetCount = getAssetCount(); // Initialise arrays // Price of each asset in USD in 1e18 outputs = new uint256[](assetCount); for (uint256 i = 0; i < allAssets.length; i++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[i]); // Get the proportional amount of this token for the redeem in 1e18 uint256 proportionalAmount = _checkBalance(allAssets[i]) .scaleBy(int8(18 - assetDecimals)) .mul(_amount) .div(totalBalance); if (proportionalAmount > 0) { // Running USD total of all coins in the redeem outputs in 1e18 totalOutputValue += proportionalAmount.mulTruncate( assetPrices[i] ); // Save the output amount in the decimals of the asset outputs[i] = proportionalAmount.scaleBy( int8(assetDecimals - 18) ); } } // USD difference in amount of coins calculated due to variations in // price in 1e18 int256 outputValueDiff = int256(_amount - totalOutputValue); // Make up the difference by adding/removing an equal proportion of // each coin according to its USD value for (uint256 i = 0; i < outputs.length; i++) { if (outputs[i] == 0) continue; if (outputValueDiff < 0) { outputs[i] -= uint256(-outputValueDiff).mul(outputs[i]).div( totalOutputValue ); } else if (outputValueDiff > 0) { outputs[i] += uint256(outputValueDiff).mul(outputs[i]).div( totalOutputValue ); } } } /** * @notice Get an array of the supported asset prices in USD. * @return uint256[] Array of asset prices in USD (1e18) */ function _getAssetPrices(bool useMax) internal returns (uint256[] memory assetPrices) { assetPrices = new uint256[](getAssetCount()); IMinMaxOracle oracle = IMinMaxOracle(priceProvider); // Price from Oracle is returned with 8 decimals // _amount is in assetDecimals for (uint256 i = 0; i < allAssets.length; i++) { string memory symbol = Helpers.getSymbol(allAssets[i]); // Get all the USD prices of the asset in 1e18 if (useMax) { assetPrices[i] = oracle.priceMax(symbol).scaleBy(int8(18 - 8)); } else { assetPrices[i] = oracle.priceMin(symbol).scaleBy(int8(18 - 8)); } } } /*************************************** Pause ****************************************/ /** * @dev Set the deposit paused flag to true to prevent rebasing. */ function pauseRebase() external onlyGovernor { rebasePaused = true; } /** * @dev Set the deposit paused flag to true to allow rebasing. */ function unpauseRebase() external onlyGovernor { rebasePaused = false; } /** * @dev Set the deposit paused flag to true to prevent deposits. */ function pauseDeposits() external onlyGovernor { depositPaused = true; emit DepositsPaused(); } /** * @dev Set the deposit paused flag to false to enable deposits. */ function unpauseDeposits() external onlyGovernor { depositPaused = false; emit DepositsUnpaused(); } /*************************************** Utils ****************************************/ /** * @dev Return the number of assets suppported by the Vault. */ function getAssetCount() public view returns (uint256) { return allAssets.length; } /** * @dev Return all asset addresses in order */ function getAllAssets() external view returns (address[] memory) { return allAssets; } /** * @dev Return the number of strategies active on the Vault. */ function getStrategyCount() public view returns (uint256) { return allStrategies.length; } /** * @dev Get the total APR of the Vault and all Strategies. */ function getAPR() external returns (uint256) { if (getStrategyCount() == 0) return 0; uint256[] memory assetPrices = _getAssetPrices(true); uint256 totalAPR = 0; // Get the value from strategies for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.getAPR() > 0) { totalAPR += _totalValueInStrategy(allStrategies[i], assetPrices) .divPrecisely(_totalValue(assetPrices)) .mulTruncate(strategy.getAPR()); } } return totalAPR; } /** * @dev Transfer token to governor. Intended for recovering tokens stuck in * contract, i.e. mistaken sends. * @param _asset Address for the asset * @param _amount Amount of the asset to transfer */ function transferToken(address _asset, uint256 _amount) external onlyGovernor { IERC20(_asset).transfer(governor(), _amount); } /** * @dev Collect reward tokens from all strategies. */ function collectRewardTokens() external onlyGovernor { for (uint256 i = 0; i < allStrategies.length; i++) { collectRewardTokens(allStrategies[i]); } } /** * @dev Collect reward tokens from a single strategy and transfer them to Vault. * @param _strategyAddr Address of the strategy to collect rewards from */ function collectRewardTokens(address _strategyAddr) public onlyGovernor { IStrategy strategy = IStrategy(_strategyAddr); strategy.collectRewardToken(); } /** * @dev Determines if an asset is supported by the vault. * @param _asset Address of the asset */ function isSupportedAsset(address _asset) external view returns (bool) { return assets[_asset].isSupported; } function _priceUSDMint(string memory symbol) internal returns (uint256) { // Price from Oracle is returned with 8 decimals // scale to 18 so 18-8=10 return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10); } /** * @dev Returns the total price in 18 digit USD for a given asset. * Using Min since min is what we use for mint pricing * @param symbol String symbol of the asset * @return uint256 USD price of 1 of the asset */ function priceUSDMint(string calldata symbol) external returns (uint256) { return _priceUSDMint(symbol); } /** * @dev Returns the total price in 18 digit USD for a given asset. * Using Max since max is what we use for redeem pricing * @param symbol String symbol of the asset * @return uint256 USD price of 1 of the asset */ function _priceUSDRedeem(string memory symbol) internal returns (uint256) { // Price from Oracle is returned with 8 decimals // scale to 18 so 18-8=10 return IMinMaxOracle(priceProvider).priceMax(symbol).scaleBy(10); } /** * @dev Returns the total price in 18 digit USD for a given asset. * Using Max since max is what we use for redeem pricing * @param symbol String symbol of the asset * @return uint256 USD price of 1 of the asset */ function priceUSDRedeem(string calldata symbol) external returns (uint256) { // Price from Oracle is returned with 8 decimals // scale to 18 so 18-8=10 return _priceUSDRedeem(symbol); } }
Price from Oracle is returned with 8 decimals scale to 18 so 18-8=10
function _priceUSDMint(string memory symbol) internal returns (uint256) { return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10); }
1,233,242
[ 1, 5147, 628, 28544, 353, 2106, 598, 1725, 15105, 3159, 358, 6549, 1427, 6549, 17, 28, 33, 2163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 8694, 3378, 16125, 474, 12, 1080, 3778, 3273, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 467, 17454, 23601, 12, 8694, 2249, 2934, 8694, 2930, 12, 7175, 2934, 5864, 858, 12, 2163, 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 ]
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/src/abstracts/SablierV2Lockup.sol
@dev Checks that `streamId` does not reference a null stream.
modifier notNull(uint256 streamId) { if (!isStream(streamId)) { revert Errors.SablierV2Lockup_Null(streamId); } _; }
9,308,371
[ 1, 4081, 716, 1375, 3256, 548, 68, 1552, 486, 2114, 279, 446, 1407, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 7713, 12, 11890, 5034, 21035, 13, 288, 203, 3639, 309, 16051, 291, 1228, 12, 3256, 548, 3719, 288, 203, 5411, 15226, 9372, 18, 55, 378, 9800, 58, 22, 2531, 416, 67, 2041, 12, 3256, 548, 1769, 203, 3639, 289, 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 ]
./full_match/1/0x2e8617079e97Ac78fCE7a2A2ec7c4a84492b805e/sources/contracts/core/Liq.sol
* @dev Mints LIQ to a given user based on the BAL supply schedule./ dont error just return. if a shutdown happens, rewards on old system can still be claimed, just wont mint cvx e.g. 100 < 500 e.g. (new) reduction = (500 - 100) * 0.25 + 70 = 170; e.g. (new) reduction = (500 - 250) * 0.25 + 70 = 132.5; e.g. (new) reduction = (500 - 400) * 0.25 + 70 = 95; e.g. (new) amount = 1e19 * 170 / 500 = 34e17; e.g. (new) amount = 1e19 * 132.5 / 500 = 26.5e17; e.g. (new) amount = 1e19 * 95 / 500 = 19e16; e.g. amtTillMax = 5e25 - 1e25 = 4e25
function mint(address _to, uint256 _amount) external { require(totalSupply() != 0, "Not initialised"); if (msg.sender != operator) { return; } if (cliff < totalCliffs) { uint256 reduction = totalCliffs.sub(cliff).div(4).add(70); uint256 amount = _amount.mul(reduction).div(totalCliffs); uint256 amtTillMax = EMISSIONS_MAX_SUPPLY.sub(emissionsMinted); if (amount > amtTillMax) { amount = amtTillMax; } _mint(_to, amount); } }
8,317,552
[ 1, 49, 28142, 8961, 53, 358, 279, 864, 729, 2511, 603, 326, 605, 1013, 14467, 4788, 18, 19, 14046, 555, 2537, 327, 18, 309, 279, 5731, 10555, 16, 283, 6397, 603, 1592, 2619, 848, 4859, 506, 7516, 329, 16, 2537, 341, 1580, 312, 474, 8951, 92, 425, 18, 75, 18, 2130, 411, 6604, 425, 18, 75, 18, 261, 2704, 13, 20176, 273, 261, 12483, 300, 2130, 13, 225, 374, 18, 2947, 397, 16647, 273, 404, 7301, 31, 425, 18, 75, 18, 261, 2704, 13, 20176, 273, 261, 12483, 300, 16927, 13, 225, 374, 18, 2947, 397, 16647, 273, 29805, 18, 25, 31, 425, 18, 75, 18, 261, 2704, 13, 20176, 273, 261, 12483, 300, 7409, 13, 225, 374, 18, 2947, 397, 16647, 273, 16848, 31, 425, 18, 75, 18, 261, 2704, 13, 3844, 273, 404, 73, 3657, 225, 404, 7301, 342, 6604, 273, 225, 13438, 73, 4033, 31, 425, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 3903, 288, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 480, 374, 16, 315, 1248, 30372, 8863, 203, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3726, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 830, 3048, 411, 2078, 2009, 430, 2556, 13, 288, 203, 5411, 2254, 5034, 20176, 273, 2078, 2009, 430, 2556, 18, 1717, 12, 830, 3048, 2934, 2892, 12, 24, 2934, 1289, 12, 7301, 1769, 203, 5411, 2254, 5034, 3844, 273, 389, 8949, 18, 16411, 12, 1118, 4062, 2934, 2892, 12, 4963, 2009, 430, 2556, 1769, 203, 5411, 2254, 5034, 25123, 56, 737, 2747, 273, 7141, 45, 4475, 55, 67, 6694, 67, 13272, 23893, 18, 1717, 12, 351, 1054, 1115, 49, 474, 329, 1769, 203, 5411, 309, 261, 8949, 405, 25123, 56, 737, 2747, 13, 288, 203, 7734, 3844, 273, 25123, 56, 737, 2747, 31, 203, 5411, 289, 203, 5411, 389, 81, 474, 24899, 869, 16, 3844, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xD3e17fb75F23fc2b176D3c08de68Ac569e1F0053/sources/contracts/Limelight.sol
* @dev An ERC20 token for LMLT. Besides the addition of voting capabilities, we make a couple of customisations: - Airdrop claim functionality via `claimTokens`. At creation time the tokens that should be available for the airdrop are transferred to the token contract address; airdrop claims are made from this balance. - Support for the owner (the DAO) to mint new tokens, at up to 1% PA./
contract LimelightToken is ERC20, ERC20Permit, ERC20Votes, Ownable { using BitMaps for BitMaps.BitMap; uint256 public constant minimumMintInterval = 365 days; bytes32 public merkleRoot; BitMaps.BitMap private claimed; event MerkleRootChanged(bytes32 merkleRoot); event Claim(address indexed claimant, uint256 amount); constructor() ERC20("Limelight", "LMLT") ERC20Permit("Limelight") import "@openzeppelin/contracts/access/Ownable.sol"; { _mint(msg.sender, freeSupply * 1e18); _mint(address(this), airdropSupply * 1e18); claimPeriodEnds = _claimPeriodEnds; nextMint = block.timestamp + minimumMintInterval; } function claimTokens(uint256 amount, address delegate, bytes32[] calldata merkleProof) external { bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount)); (bool valid, uint256 index) = MerkleProof.verify(merkleProof, merkleRoot, leaf); require(valid, "LMLT: Valid proof required."); require(!isClaimed(index), "LMLT: Tokens already claimed."); claimed.set(index); emit Claim(msg.sender, amount); _delegate(msg.sender, delegate); _transfer(address(this), msg.sender, amount); } function sweep(address dest) external onlyOwner { require(block.timestamp > claimPeriodEnds, "LMLT: Claim period not yet ended"); _transfer(address(this), dest, balanceOf(address(this))); } function isClaimed(uint256 index) public view returns (bool) { return claimed.get(index); } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { require(merkleRoot == bytes32(0), "LMLT: Merkle root already set"); merkleRoot = _merkleRoot; emit MerkleRootChanged(_merkleRoot); } function mint(address dest, uint256 amount) external onlyOwner { require(amount <= (totalSupply() * mintCap) / 10000, "LMLT: Mint exceeds maximum amount"); require(block.timestamp >= nextMint, "LMLT: Cannot mint yet"); nextMint = block.timestamp + minimumMintInterval; _mint(dest, amount); } function _afterTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Votes) { super._afterTokenTransfer(from, to, amount); } function _mint(address to, uint256 amount) internal override(ERC20, ERC20Votes) { super._mint(to, amount); } function _burn(address account, uint256 amount) internal override(ERC20, ERC20Votes) { super._burn(account, amount); } }
12,462,116
[ 1, 979, 4232, 39, 3462, 1147, 364, 511, 1495, 56, 18, 1377, 605, 281, 4369, 326, 2719, 434, 331, 17128, 12359, 16, 732, 1221, 279, 1825, 2268, 434, 1679, 291, 1012, 30, 4202, 300, 432, 6909, 1764, 7516, 14176, 3970, 1375, 14784, 5157, 8338, 2380, 6710, 813, 326, 2430, 716, 540, 1410, 506, 2319, 364, 326, 279, 6909, 1764, 854, 906, 4193, 358, 326, 1147, 6835, 1758, 31, 540, 279, 6909, 1764, 11955, 854, 7165, 628, 333, 11013, 18, 4202, 300, 13619, 364, 326, 3410, 261, 5787, 463, 20463, 13, 358, 312, 474, 394, 2430, 16, 622, 731, 358, 404, 9, 15662, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 511, 381, 292, 750, 1345, 353, 4232, 39, 3462, 16, 4232, 39, 3462, 9123, 305, 16, 4232, 39, 3462, 29637, 16, 14223, 6914, 288, 203, 565, 1450, 6539, 8903, 364, 6539, 8903, 18, 5775, 863, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 5224, 49, 474, 4006, 273, 21382, 4681, 31, 203, 203, 565, 1731, 1578, 1071, 30235, 2375, 31, 203, 565, 6539, 8903, 18, 5775, 863, 3238, 7516, 329, 31, 203, 203, 565, 871, 31827, 2375, 5033, 12, 3890, 1578, 30235, 2375, 1769, 203, 565, 871, 18381, 12, 2867, 8808, 7516, 970, 16, 2254, 5034, 3844, 1769, 203, 203, 203, 565, 3885, 1435, 203, 3639, 4232, 39, 3462, 2932, 48, 381, 292, 750, 3113, 315, 48, 1495, 56, 7923, 203, 3639, 4232, 39, 3462, 9123, 305, 2932, 48, 381, 292, 750, 7923, 203, 5666, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 3860, 19, 5460, 429, 18, 18281, 14432, 203, 565, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 4843, 3088, 1283, 380, 404, 73, 2643, 1769, 203, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 279, 6909, 1764, 3088, 1283, 380, 404, 73, 2643, 1769, 203, 3639, 7516, 5027, 24980, 273, 389, 14784, 5027, 24980, 31, 203, 3639, 1024, 49, 474, 273, 1203, 18, 5508, 397, 5224, 49, 474, 4006, 31, 203, 565, 289, 203, 203, 565, 445, 7516, 5157, 12, 11890, 5034, 3844, 16, 1758, 7152, 16, 1731, 1578, 8526, 745, 892, 30235, 20439, 13, 3903, 288, 203, 3639, 1731, 1578, 7839, 273, 2 ]
./full_match/11155111/0x9620d66Dab07e8CC21C1622639a4206a6f324a86/sources/libs/NFTDescriptor.sol
* @notice Construct an ERC721 token URI./
function constructTokenURI(TokenURIParams memory params) public pure returns (string memory) { string memory image = generateSVGImage( MultiPartSVGsToSVG.SVGParams({ parts: params.parts, background: params.background, role: params.role, fill: params.fill, outline: params.outline }) ); abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( ) ) ) ); }
3,794,071
[ 1, 7249, 392, 4232, 39, 27, 5340, 1147, 3699, 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, 4872, 1345, 3098, 12, 1345, 3098, 1370, 3778, 859, 13, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 533, 3778, 1316, 273, 2103, 26531, 2040, 12, 203, 5411, 5991, 1988, 26531, 11634, 26531, 18, 26531, 1370, 12590, 203, 7734, 2140, 30, 859, 18, 6019, 16, 203, 7734, 5412, 30, 859, 18, 9342, 16, 203, 7734, 2478, 30, 859, 18, 4615, 16, 203, 7734, 3636, 30, 859, 18, 5935, 16, 203, 7734, 16363, 30, 859, 18, 25134, 203, 5411, 289, 13, 203, 3639, 11272, 203, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 296, 892, 30, 3685, 19, 1977, 31, 1969, 1105, 16, 2187, 203, 7734, 3360, 1105, 18, 3015, 12, 203, 10792, 1731, 12, 203, 10792, 262, 203, 7734, 262, 203, 5411, 262, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/math/Math.sol pragma solidity 0.5.17; library Math { function MAX311(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN896(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE467(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity 0.5.17; library SafeMath { function ADD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB912(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB912(a, b, "SafeMath: subtraction overflow"); } function SUB912(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL612(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV645(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV645(a, b, "SafeMath: division by zero"); } function DIV645(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD528(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD528(a, b, "SafeMath: modulo by zero"); } function MOD528(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity 0.5.17; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal {} // solhint-disable-previous-line no-empty-blocks function _MSGSENDER219() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA337() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity 0.5.17; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED705(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER219(); emit OWNERSHIPTRANSFERRED705(address(0), _owner); } function OWNER858() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER527() { //inject NONSTANDARD NAMING require(ISOWNER429(), "Ownable: caller is not the owner"); _; } function ISOWNER429() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER219() == _owner; } function RENOUNCEOWNERSHIP633() public ONLYOWNER527 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED705(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP10(address newOwner) public ONLYOWNER527 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP120(newOwner); } function _TRANSFEROWNERSHIP120(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED705(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity 0.5.17; interface IERC20 { function TOTALSUPPLY2() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF265(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER164(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINT263(address account, uint amount) external; //inject NONSTANDARD NAMING function BURN805(uint amount) external; //inject NONSTANDARD NAMING function ALLOWANCE538(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE42(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM15(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINTERS951(address account) external view returns (bool); //inject NONSTANDARD NAMING event TRANSFER380(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL481(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity 0.5.17; library Address { function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly {codehash := extcodehash(account)} return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE864(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE732(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success,) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity 0.5.17; library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER450(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFER164.selector, to, value)); } function SAFETRANSFERFROM145(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFERFROM15.selector, from, to, value)); } function SAFEAPPROVE302(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE538(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, value)); } function SAFEINCREASEALLOWANCE445(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE538(address(this), spender).ADD124(value); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE538(address(this), spender).SUB912(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance)); } function CALLOPTIONALRETURN337(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT794(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) {// Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/IRewardDistributionRecipient.sol pragma solidity 0.5.17; contract IRewardDistributionRecipient is Ownable { address public rewardReferral; function NOTIFYREWARDAMOUNT832(uint256 reward) external; //inject NONSTANDARD NAMING function SETREWARDREFERRAL334(address _rewardReferral) external ONLYOWNER527 { //inject NONSTANDARD NAMING rewardReferral = _rewardReferral; } } // File: contracts/CurveRewards.sol pragma solidity 0.5.17; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; IERC20 public yfv = IERC20(0x45f24BaEef268BB6d63AEe5129015d69702BCDfa); uint256 private _totalSupply; mapping(address => uint256) private _balances; function TOTALSUPPLY2() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF265(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TOKENSTAKE952(uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD124(actualStakeAmount); _balances[msg.sender] = _balances[msg.sender].ADD124(actualStakeAmount); yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount); } function TOKENSTAKEONBEHALF333(address stakeFor, uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD124(actualStakeAmount); _balances[stakeFor] = _balances[stakeFor].ADD124(actualStakeAmount); yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount); } function TOKENWITHDRAW537(uint256 amount, uint256 actualWithdrawAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.SUB912(amount); _balances[msg.sender] = _balances[msg.sender].SUB912(amount); yfv.SAFETRANSFER450(msg.sender, actualWithdrawAmount); } } interface IYFVReferral { function SETREFERRER414(address farmer, address referrer) external; //inject NONSTANDARD NAMING function GETREFERRER855(address farmer) external view returns (address); //inject NONSTANDARD NAMING } contract YFVStakeV2 is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public vUSD = IERC20(0x1B8E12F839BD4e73A47adDF76cF7F0097d74c14C); IERC20 public vETH = IERC20(0x76A034e76Aa835363056dd418611E4f81870f16e); uint256 public vETH_REWARD_FRACTION_RATE = 1000; uint256 public constant duration178 = 7 days; //inject NONSTANDARD NAMING uint8 public constant number_epochs944 = 38; //inject NONSTANDARD NAMING uint256 public constant referral_commission_percent277 = 1; //inject NONSTANDARD NAMING uint256 public currentEpochReward = 0; uint256 public totalAccumulatedReward = 0; uint8 public currentEpoch = 0; uint256 public starttime = 1598968800; // Tuesday, September 1, 2020 2:00:00 PM (GMT+0) uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public constant default_epoch_reward278 = 230000 * (10 ** 9); // 230,000 vUSD (and 230 vETH) //inject NONSTANDARD NAMING uint256 public constant total_reward44 = default_epoch_reward278 * number_epochs944; // 8,740,000 vUSD (and 8,740 vETH) //inject NONSTANDARD NAMING uint256 public epochReward = default_epoch_reward278; uint256 public minStakingAmount = 90 ether; uint256 public unstakingFrozenTime = 40 hours; // ** DISABLED AT BEGINNING - WILL SET IT BY GOVERNANCE AFTER VIP-1.1 // ** unlockWithdrawFee = 0.1%: stakers will need to pay 0.1% (sent to insurance fund)of amount they want to withdraw if the coin still frozen // ** lowStakeDepositFee = 0.1%: stakers still can stake with low amount but need to pay 0.1% (sent to insurance fund) // specially, if lowStakeDepositFee = 10000 -> low amount stakers will not pay anything (richmen pay tax, not poormen) // ** highStakeDepositFee = 0.1%: stakers need to pay 0.1% of extra amount more than 90 YFV (sent to insurance fund) uint256 public lowStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%) uint256 public highStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%) uint256 public unlockWithdrawFee = 0; // per ten thousand (eg. 15 -> 0.15%) address public yfvInsuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public lastStakeTimes; mapping(address => uint256) public accumulatedStakingPower; // will accumulate every time staker does getReward() mapping(address => bool) public whitelistedPools; // for stake on behalf event REWARDADDED885(uint256 reward); //inject NONSTANDARD NAMING event YFVREWARDADDED261(uint256 reward); //inject NONSTANDARD NAMING event BURNED28(uint256 reward); //inject NONSTANDARD NAMING event STAKED939(address indexed user, uint256 amount, uint256 actualStakeAmount); //inject NONSTANDARD NAMING event WITHDRAWN649(address indexed user, uint256 amount, uint256 actualWithdrawAmount); //inject NONSTANDARD NAMING event REWARDPAID896(address indexed user, uint256 reward); //inject NONSTANDARD NAMING event COMMISSIONPAID234(address indexed user, uint256 reward); //inject NONSTANDARD NAMING constructor() public { whitelistedPools[0x62a9fE913eb596C8faC0936fd2F51064022ba22e] = true; // BAL Pool whitelistedPools[0x70b83A7f5E83B3698d136887253E0bf426C9A117] = true; // YFI Pool whitelistedPools[0x1c990fC37F399C935625b815975D0c9fAD5C31A1] = true; // BAT Pool whitelistedPools[0x752037bfEf024Bd2669227BF9068cb22840174B0] = true; // REN Pool whitelistedPools[0x9b74774f55C0351fD064CfdfFd35dB002C433092] = true; // KNC Pool whitelistedPools[0xFBDE07329FFc9Ec1b70f639ad388B94532b5E063] = true; // BTC Pool whitelistedPools[0x67FfB615EAEb8aA88fF37cCa6A32e322286a42bb] = true; // ETH Pool whitelistedPools[0x196CF719251579cBc850dED0e47e972b3d7810Cd] = true; // LINK Pool whitelistedPools[msg.sender] = true; // to be able to stakeOnBehalf farmer who have stucked fund in Pool Stake v1. } function ADDWHITELISTEDPOOL116(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING whitelistedPools[_addressPool] = true; } function REMOVEWHITELISTEDPOOL972(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING whitelistedPools[_addressPool] = false; } function SETYFVINSURANCEFUND27(address _yfvInsuranceFund) public ONLYOWNER527 { //inject NONSTANDARD NAMING yfvInsuranceFund = _yfvInsuranceFund; } function SETEPOCHREWARD899(uint256 _epochReward) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_epochReward <= default_epoch_reward278 * 10, "Insane big _epochReward!"); // At most 10x only epochReward = _epochReward; } function SETMINSTAKINGAMOUNT151(uint256 _minStakingAmount) public ONLYOWNER527 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function SETUNSTAKINGFROZENTIME482(uint256 _unstakingFrozenTime) public ONLYOWNER527 { //inject NONSTANDARD NAMING unstakingFrozenTime = _unstakingFrozenTime; } function SETSTAKEDEPOSITFEE451(uint256 _lowStakeDepositFee, uint256 _highStakeDepositFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_lowStakeDepositFee <= 100 || _lowStakeDepositFee == 10000, "Dont be too greedy"); // <= 1% OR set to 10000 to disable low stake fee require(_highStakeDepositFee <= 100, "Dont be too greedy"); // <= 1% lowStakeDepositFee = _lowStakeDepositFee; highStakeDepositFee = _highStakeDepositFee; } function SETUNLOCKWITHDRAWFEE126(uint256 _unlockWithdrawFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_unlockWithdrawFee <= 1000, "Dont be too greedy"); // <= 10% unlockWithdrawFee = _unlockWithdrawFee; } // To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade) function UPGRADEVUSDCONTRACT293(address _vUSDContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING vUSD = IERC20(_vUSDContract); } // To upgrade vETH contract (v1 is still experimental, we may need vETHv2 with rebase() function working soon - then governance will call this upgrade) function UPGRADEVETHCONTRACT116(address _vETHContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING vETH = IERC20(_vETHContract); } modifier UPDATEREWARD641(address account) { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN11(); lastUpdateTime = LASTTIMEREWARDAPPLICABLE544(); if (account != address(0)) { rewards[account] = EARNED432(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function LASTTIMEREWARDAPPLICABLE544() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN896(block.timestamp, periodFinish); } function REWARDPERTOKEN11() public view returns (uint256) { //inject NONSTANDARD NAMING if (TOTALSUPPLY2() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD124( LASTTIMEREWARDAPPLICABLE544() .SUB912(lastUpdateTime) .MUL612(rewardRate) .MUL612(1e18) .DIV645(TOTALSUPPLY2()) ); } // vUSD balance function EARNED432(address account) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 calculatedEarned = BALANCEOF265(account) .MUL612(REWARDPERTOKEN11().SUB912(userRewardPerTokenPaid[account])) .DIV645(1e18) .ADD124(rewards[account]); uint256 poolBalance = vUSD.BALANCEOF265(address(this)); // some rare case the reward can be slightly bigger than real number, we need to check against how much we have left in pool if (calculatedEarned > poolBalance) return poolBalance; return calculatedEarned; } function STAKINGPOWER96(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return accumulatedStakingPower[account].ADD124(EARNED432(account)); } function VETHBALANCE317(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return EARNED432(account).DIV645(vETH_REWARD_FRACTION_RATE); } function STAKE230(uint256 amount, address referrer) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount >= 1 szabo, "Do not stake dust"); require(referrer != msg.sender, "You cannot refer yourself."); uint256 actualStakeAmount = amount; uint256 depositFee = 0; if (minStakingAmount > 0) { if (amount < minStakingAmount && lowStakeDepositFee < 10000) { // if amount is less than minStakingAmount and lowStakeDepositFee is not disabled // if governance does not allow low stake if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount"); // otherwise depositFee will be calculated based on the rate else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000); } else if (amount > minStakingAmount && highStakeDepositFee > 0) { // if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount) depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000); } if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); } } super.TOKENSTAKE952(amount, actualStakeAmount); lastStakeTimes[msg.sender] = block.timestamp; emit STAKED939(msg.sender, amount, actualStakeAmount); if (depositFee > 0) { if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee); emit REWARDPAID896(yfvInsuranceFund, depositFee); } else { // or burn yfv.BURN805(depositFee); emit BURNED28(depositFee); } } if (rewardReferral != address(0) && referrer != address(0)) { IYFVReferral(rewardReferral).SETREFERRER414(msg.sender, referrer); } } function STAKEONBEHALF204(address stakeFor, uint256 amount) public UPDATEREWARD641(stakeFor) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount >= 1 szabo, "Do not stake dust"); require(whitelistedPools[msg.sender], "Sorry hackers, you should stay away from us (YFV community signed)"); uint256 actualStakeAmount = amount; uint256 depositFee = 0; if (minStakingAmount > 0) { if (amount < minStakingAmount && lowStakeDepositFee < 10000) { // if amount is less than minStakingAmount and lowStakeDepositFee is not disabled // if governance does not allow low stake if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount"); // otherwise depositFee will be calculated based on the rate else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000); } else if (amount > minStakingAmount && highStakeDepositFee > 0) { // if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount) depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000); } if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); } } super.TOKENSTAKEONBEHALF333(stakeFor, amount, actualStakeAmount); lastStakeTimes[stakeFor] = block.timestamp; emit STAKED939(stakeFor, amount, actualStakeAmount); if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee); emit REWARDPAID896(yfvInsuranceFund, depositFee); } else { // or burn yfv.BURN805(depositFee); emit BURNED28(depositFee); } } } function UNFROZENSTAKETIME568(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return lastStakeTimes[account] + unstakingFrozenTime; } function WITHDRAW21(uint256 amount) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount > 0, "Cannot withdraw 0"); uint256 actualWithdrawAmount = amount; if (block.timestamp < UNFROZENSTAKETIME568(msg.sender)) { // if coin is still frozen and governance does not allow stakers to unstake before timer ends if (unlockWithdrawFee == 0) revert("Coin is still frozen"); // otherwise withdrawFee will be calculated based on the rate uint256 withdrawFee = amount.MUL612(unlockWithdrawFee).DIV645(10000); actualWithdrawAmount = amount.SUB912(withdrawFee); if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, withdrawFee); emit REWARDPAID896(yfvInsuranceFund, withdrawFee); } else { // or burn yfv.BURN805(withdrawFee); emit BURNED28(withdrawFee); } } super.TOKENWITHDRAW537(amount, actualWithdrawAmount); emit WITHDRAWN649(msg.sender, amount, actualWithdrawAmount); } function EXIT848() external { //inject NONSTANDARD NAMING WITHDRAW21(BALANCEOF265(msg.sender)); GETREWARD938(); } function GETREWARD938() public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { accumulatedStakingPower[msg.sender] = accumulatedStakingPower[msg.sender].ADD124(rewards[msg.sender]); rewards[msg.sender] = 0; vUSD.SAFETRANSFER450(msg.sender, reward); vETH.SAFETRANSFER450(msg.sender, reward.DIV645(vETH_REWARD_FRACTION_RATE)); emit REWARDPAID896(msg.sender, reward); } } modifier CHECKNEXTEPOCH825() { //inject NONSTANDARD NAMING require(periodFinish > 0, "Pool has not started"); if (block.timestamp >= periodFinish) { currentEpochReward = epochReward; if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) { currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward } if (currentEpochReward > 0) { if (!vUSD.MINTERS951(address(this)) || !vETH.MINTERS951(address(this))) { currentEpochReward = 0; } else { vUSD.MINT263(address(this), currentEpochReward); vETH.MINT263(address(this), currentEpochReward.DIV645(vETH_REWARD_FRACTION_RATE)); totalAccumulatedReward = totalAccumulatedReward.ADD124(currentEpochReward); } currentEpoch++; } rewardRate = currentEpochReward.DIV645(duration178); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.ADD124(duration178); emit REWARDADDED885(currentEpochReward); } _; } // Start the pool with reward amount for this epoch function NOTIFYREWARDAMOUNT832(uint256 reward) external ONLYOWNER527 UPDATEREWARD641(address(0)) { //inject NONSTANDARD NAMING require(periodFinish == 0, "Only can call once to start staking"); currentEpochReward = reward; if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) { currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward } lastUpdateTime = block.timestamp; if (block.timestamp < starttime) { // epoch zero periodFinish = starttime; rewardRate = reward.DIV645(periodFinish.SUB912(block.timestamp)); } else { // 1st epoch periodFinish = lastUpdateTime.ADD124(duration178); rewardRate = reward.DIV645(duration178); currentEpoch++; } vUSD.MINT263(address(this), reward); vETH.MINT263(address(this), reward.DIV645(vETH_REWARD_FRACTION_RATE)); totalAccumulatedReward = totalAccumulatedReward.ADD124(reward); emit REWARDADDED885(reward); } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function GOVERNANCERECOVERUNSUPPORTED727(IERC20 _token, uint256 amount, address to) external { //inject NONSTANDARD NAMING // only gov require(msg.sender == OWNER858(), "!governance"); // cant take staked asset require(_token != yfv, "yfv"); // cant take reward asset require(_token != vUSD, "vUSD"); require(_token != vETH, "vETH"); // transfer to _token.SAFETRANSFER450(to, amount); } }
inject NONSTANDARD NAMING
function LASTTIMEREWARDAPPLICABLE544() public view returns (uint256) {
7,225,476
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15612, 56, 31582, 7245, 8085, 7215, 6065, 2782, 25, 6334, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-24 */ // Sources flattened with hardhat v2.8.3 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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; } } // File @openzeppelin/contracts/math/[email protected] 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/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File @openzeppelin/contracts/utils/[email protected] 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/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File @openzeppelin/contracts/introspection/[email protected] 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/[email protected] 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/[email protected] 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/token/ERC721/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() 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()); } } // File contracts/interfaces/IMarketplace.sol /** *Submitted for verification at Etherscan.io on 2021-12-08 */ pragma solidity ^0.7.0; interface IMarketplace { struct Order { // Order ID bytes32 id; // Owner of the NFT address seller; // NFT registry address address nftAddress; // Price (in wei) for the published item uint256 price; } struct Bid { // Bid Id bytes32 id; // Bidder address address bidder; // Price for the bid in wei uint256 price; } // ORDER EVENTS event OrderCreated( bytes32 id, address indexed seller, address indexed nftAddress, uint256 indexed assetId, uint256 priceInWei ); event OrderUpdated(bytes32 id, uint256 priceInWei); event OrderSuccessful( bytes32 id, address indexed buyer, uint256 priceInWei ); event OrderCancelled(bytes32 id); // BID EVENTS event purchaseOrderEvent( bytes32 id, address indexed nftAddress, uint256 indexed assetId, address indexed bidder, uint256 priceInWei ); event BidAccepted(bytes32 id); event BidCancelled(bytes32 id); } // File contracts/EmillionMarketplace.sol pragma solidity ^0.7.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } interface Iemillionnft { function getArtist(uint256 id) external view returns (address); } contract EmillionNftMarketPlace is Ownable, Pausable, IMarketplace, ERC721Holder { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; Iemillionnft public iemillionnft; address public WETH; // From ERC721 registry assetId to Order (to avoid asset collision) mapping(address => mapping(uint256 => Order)) public orderByAssetId; // 721 Interfaces bytes4 public constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor(address _nft, address _WETH) { WETH = _WETH; iemillionnft = Iemillionnft(_nft); } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH } function withdrawETH() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "ETH balance is 0"); msg.sender.transfer(address(this).balance); } function withdWETH() external onlyOwner { require( IERC20(WETH).balanceOf(address(this)) > 0, "low balance of weth" ); IERC20(WETH).transfer( msg.sender, IERC20(WETH).balanceOf(address(this)) ); } /** * @dev Sets the paused failsafe. Can only be called by owner * @param _setPaused - paused state */ function setPaused(bool _setPaused) public onlyOwner { return (_setPaused) ? _pause() : _unpause(); } /** * @dev Creates a new order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT */ function createOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei ) public whenNotPaused { _createOrder(_nftAddress, _assetId, _priceInWei); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function cancelOrder(address _nftAddress, uint256 _assetId) public whenNotPaused { Order memory order = orderByAssetId[_nftAddress][_assetId]; require( order.seller == msg.sender || msg.sender == owner(), "Marketplace: unauthorized sender" ); // Cancel order. _cancelOrder(order.id, _nftAddress, _assetId, msg.sender); } function getArtistAddress(uint256 _id) public view returns (address) { return iemillionnft.getArtist(_id); } /** * @dev Update an already published order * can only be updated by seller * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function updateOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei ) public whenNotPaused { Order storage order = orderByAssetId[_nftAddress][_assetId]; // Check valid order to update require(order.id != 0, "Marketplace: asset not published"); require(order.seller == msg.sender, "Marketplace: sender not allowed"); // check order updated params require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); order.price = _priceInWei; emit OrderUpdated(order.id, _priceInWei); } function purchaseOrder(address _nftAddress, uint256 _assetId) public payable whenNotPaused { IWETH(WETH).deposit{value: msg.value}(); _purchaseOrder(_nftAddress, _assetId, msg.value); } /** * @dev Internal function gets Order by nftRegistry and assetId. Checks for the order validity * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function _getValidOrder(address _nftAddress, uint256 _assetId) internal view returns (Order memory order) { order = orderByAssetId[_nftAddress][_assetId]; require(order.id != 0, "Marketplace: asset not published"); return order; } /** * @dev Executes the sale for a published NFT * @param _orderId - Order Id to execute * @param _buyer - address * @param _nftAddress - Address of the NFT registry * @param _assetId - NFT id * @param _priceInWei - Order price */ function _executeOrder( bytes32 _orderId, address _buyer, address _nftAddress, uint256 _assetId, uint256 _priceInWei ) internal { // remove order delete orderByAssetId[_nftAddress][_assetId]; // Transfer NFT asset IERC721(_nftAddress).safeTransferFrom(address(this), _buyer, _assetId); // Notify ... emit OrderSuccessful(_orderId, _buyer, _priceInWei); } /** * @dev Creates a new order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin */ function _createOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei ) internal { // Check nft registry IERC721 nftRegistry = _requireERC721(_nftAddress); // Check order creator is the asset owner address assetOwner = nftRegistry.ownerOf(_assetId); require( assetOwner == msg.sender, "Marketplace: Only the asset owner can create orders" ); require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); // get NFT asset from seller nftRegistry.safeTransferFrom(assetOwner, address(this), _assetId); // create the orderId bytes32 orderId = keccak256( abi.encodePacked( block.timestamp, assetOwner, _nftAddress, _assetId, _priceInWei ) ); // save order orderByAssetId[_nftAddress][_assetId] = Order({ id: orderId, seller: assetOwner, nftAddress: _nftAddress, price: _priceInWei }); emit OrderCreated( orderId, assetOwner, _nftAddress, _assetId, _priceInWei ); } /** * @dev Creates a new bid on a existing order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin */ function _purchaseOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei ) internal { // Checks order validity Order memory order = _getValidOrder(_nftAddress, _assetId); require( _priceInWei == order.price, "Marketplace: bid should be = order price" ); // Create bid bytes32 bidId = keccak256( abi.encodePacked(block.timestamp, msg.sender, order.id, _priceInWei) ); IWETH(WETH).transfer(order.seller, (order.price).mul(9500).div(10000)); IWETH(WETH).transfer( getArtistAddress(_assetId), (order.price).mul(375).div(10000) ); // IWETH(WETH).transfer(address(this), (order.price).mul(125).div(10000)); _executeOrder(order.id, msg.sender, _nftAddress, _assetId, order.price); emit purchaseOrderEvent( bidId, _nftAddress, _assetId, msg.sender, _priceInWei ); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner * @param _orderId - Bid identifier * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _seller - Address */ function _cancelOrder( bytes32 _orderId, address _nftAddress, uint256 _assetId, address _seller ) internal { delete orderByAssetId[_nftAddress][_assetId]; // send asset back to seller IERC721(_nftAddress).safeTransferFrom(address(this), _seller, _assetId); emit OrderCancelled(_orderId); } function _requireERC721(address _nftAddress) internal view returns (IERC721) { require( _nftAddress.isContract(), "The NFT Address should be a contract" ); require( IERC721(_nftAddress).supportsInterface(_INTERFACE_ID_ERC721), "The NFT contract has an invalid ERC721 implementation" ); return IERC721(_nftAddress); } }
* @dev Cancel an already published order can only be canceled by seller or the contract owner @param _orderId - Bid identifier @param _nftAddress - Address of the NFT registry @param _assetId - ID of the published NFT @param _seller - Address/ send asset back to seller
function _cancelOrder( bytes32 _orderId, address _nftAddress, uint256 _assetId, address _seller ) internal { delete orderByAssetId[_nftAddress][_assetId]; IERC721(_nftAddress).safeTransferFrom(address(this), _seller, _assetId); emit OrderCancelled(_orderId); }
7,925,592
[ 1, 6691, 392, 1818, 9487, 1353, 225, 848, 1338, 506, 17271, 635, 29804, 578, 326, 6835, 3410, 225, 389, 1019, 548, 300, 605, 350, 2756, 225, 389, 82, 1222, 1887, 300, 5267, 434, 326, 423, 4464, 4023, 225, 389, 9406, 548, 300, 1599, 434, 326, 9487, 423, 4464, 225, 389, 1786, 749, 300, 5267, 19, 1366, 3310, 1473, 358, 29804, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 10996, 2448, 12, 203, 3639, 1731, 1578, 389, 1019, 548, 16, 203, 3639, 1758, 389, 82, 1222, 1887, 16, 203, 3639, 2254, 5034, 389, 9406, 548, 16, 203, 3639, 1758, 389, 1786, 749, 203, 565, 262, 2713, 288, 203, 3639, 1430, 5278, 6672, 548, 63, 67, 82, 1222, 1887, 6362, 67, 9406, 548, 15533, 203, 203, 3639, 467, 654, 39, 27, 5340, 24899, 82, 1222, 1887, 2934, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 389, 1786, 749, 16, 389, 9406, 548, 1769, 203, 203, 3639, 3626, 4347, 21890, 24899, 1019, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-02 */ // SPDX-License-Identifier: GNU AGPLv3 pragma solidity ^0.8.0; interface ILookRevTree { function addLeafToOpenBranch(uint256 genesisBranch, uint256 tokenID) external returns (uint256); function addLeavesToOpenBranches(uint256[] calldata tokenIDs) external returns (uint256); function getTokenPubID(uint256 tokenID) external view returns (string memory); function updateNFTTokenPubID(uint256 tokenID, string calldata pubID) external; } interface LookRevLeafNFT { function getNFTTokenRecipient(uint256 tokenID) external view returns (address); } interface INextTree { function migrateTokens(uint256 branch, uint256[] calldata tokenIDs, address leafNFT) external; } // File: node_modules\@openzeppelin\contracts\math\SafeMath.sol /** * @dev Patched. Wrappers over Solidity's arithmetic operations with added overflow * checks. Patched. * * 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 && c >= b, "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-contracts/pull/522 if (a == 0 || b == 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) { 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 String operations. */ library Strings { /** * @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); } } /// LookRevTree registry contract LookRevTree is ILookRevTree { struct GenesisBranch { uint256 id; string name; uint256 maxLevel; uint256 openBranch; uint256 leavesCount; uint256 baseValue; uint8 state; uint256 harvestTime; string uri; uint256 createdAt; } /// Branch structure struct Branch { uint256 id; uint256 level; uint256 genesisBranch; uint256 availableLeaves; uint256 createdAt; } /// Leaf structure struct Leaf { uint256 id; uint256 branchId; uint256 tokenID; uint256 createdAt; } /// Genesis branches mapping(uint256 => GenesisBranch) public genesisBranches; /// Mapping branch id to branches mapping(uint256 => Branch) public branches; /// Mapping genesisBranchID => level => brancheIDs mapping(uint256 => mapping(uint256 => uint256[])) public branchesAtLevel; /// Mapping leafID to leaves mapping(uint256 => Leaf) public leaves; /// Mapping tokenID => leafID mapping(uint256 => uint256) public tokenIDToLeafID; mapping(uint256 => string) private tokenIDToPubID; /// Branch operators /// Mapping genesisBranchID => operator address => approval mapping(uint256 => mapping(address => bool)) public operators; /// Index of next genesis branch uint256 public nextGenesisBranchId = 1; /// Index of next branch uint256 public nextBranchId = 1; /// Index of next leaf uint256 public nextLeafId = 1; /// Average leaf cost, set with initial value uint256 public averageLeafCost = 5 * 10 ** 16; /// Maximum level of the tree, set with initial value uint256 public treeMaxLevel = 1; /// Start time uint256 public START_TIME; /// Maximum number of leaves on a branch uint256 constant public MAX_SUPPLY = 10; /// Minimum base value of a leafNFT is 0.05 ETH uint256 public MIN_BASE_VALUE = 5 * 10 ** 16; /// Side branches count uint256 public BRANCH_UNIT = 2; /// Initial first harvest time is 100 days after the branch vest day uint256 constant public FIRST_HARVEST_TIME = (86400 * 100); uint256 constant public HARVEST_START_COUNT = 1000; string public baseURI = "https://lookrev.com/branch/"; // State 0 = OPEN, 1 = PAUSE, 2 = STOP uint8 public treeStatus; string public statusInfo; /// Address for tree upgrade address public nextTree; /// LookRevLeafNFT ERC721 contract address address public lrLeaf; address[] private leafVersions; address private admin; address private ceo; address private cfo; /// @dev Emitted when creates genesis branch event GenesisBranchCreated( uint256 indexed id, string indexed name, uint256 indexed firstAvailableBranch, uint256 count ); /// @dev Emitted when creates branch event BranchCreated( uint256 indexed id, uint256 indexed genesisBranch, uint256 indexed level ); /// @dev Emitted when adds new leaves event AddedLeaves( uint256 indexed branchID, uint256 indexed leafID, uint256 indexed tokenID, uint256 count ); /// @dev Emitted when harvest time of a branch is scheduled event HarvestTimeScheduled( uint256 indexed genesisBranchID, uint256 indexed openBranchID, uint256 leavesCount, uint256 indexed harvestTime ); /// @dev Emitted when enables or removes operator of a branch event OperatorUpdated( uint256 indexed branchID, address indexed operator, bool indexed approved ); /// @dev Emitted when updates contract event VersionUpdated( string indexed str, address indexed newaddress ); /// @dev Emitted when updates role event RoleUpdated( string indexed str, address indexed newaddress ); /// Constructor constructor() { admin = msg.sender; treeStatus = 0; } /// Create genesis branches function createGenesisBranch(string[] calldata _names) public { require(msg.sender == admin, "LookRevTree: Not authorized"); require(treeStatus == 0, "LookRevTree: Tree is currently not OPEN."); for (uint256 i = 0; i < _names.length; i++) { string memory _n = _names[i]; genesisBranches[nextGenesisBranchId] = GenesisBranch(nextGenesisBranchId, _n, 1, nextBranchId, 0, MIN_BASE_VALUE, 0, 0, string(abi.encodePacked(baseURI, Strings.toString(nextGenesisBranchId))), block.timestamp); // Create a level 1 branch branches[nextBranchId] = Branch(nextBranchId, 1, nextGenesisBranchId, MAX_SUPPLY, block.timestamp); branchesAtLevel[nextGenesisBranchId][1].push(nextBranchId); nextGenesisBranchId += 1; nextBranchId += 1; } emit GenesisBranchCreated(nextGenesisBranchId - 1, _names[0], nextBranchId - 1, _names.length); } /// Creating a branch from the genesis branch /// @param branch BranchID of the genesis branch function _createBranch(uint256 branch) internal { require(genesisBranches[branch].state == 0, "LookRevTree: Branch is not OPEN"); uint256 _maxLevel = genesisBranches[branch].maxLevel; uint256 _count = branchesAtLevel[branch][_maxLevel].length; if (_count < _maxLevel * BRANCH_UNIT) { _createNewBranch(branch, _maxLevel); } else { genesisBranches[branch].maxLevel += 1; _createNewBranch(branch, _maxLevel + 1); } } /// Creating a new branch from the genesis branch /// @dev Adding a subbranch increase the baseValue of the genesis branch /// @param branch BranchID of the genesis branch function _createNewBranch(uint256 branch, uint256 level) internal { require(treeStatus == 0, "LookRevTree: Tree is currently not OPEN."); branches[nextBranchId] = Branch(nextBranchId, level, branch, MAX_SUPPLY, block.timestamp); branchesAtLevel[branch][level].push(nextBranchId); /// increase the base value of branch when adding in subBranch genesisBranches[branch].baseValue = genesisBranches[branch].baseValue * 102 / 100; emit BranchCreated(nextBranchId, branch, level); nextBranchId += 1; // update treeMaxLevel of the tree if (level > treeMaxLevel) { treeMaxLevel = level; } } /// Get average cost of leaf on the tree function _getAverageLeafCost() internal returns (uint256) { if (nextGenesisBranchId < 3) { averageLeafCost = genesisBranches[1].baseValue; return averageLeafCost; } uint256 _sum = 0; for (uint256 i = 1; i < nextGenesisBranchId; i++) { _sum = SafeMath.add(_sum, genesisBranches[i].baseValue); } averageLeafCost = SafeMath.div(_sum, nextGenesisBranchId - 1); return averageLeafCost; } /// Add new leaf to an open branch, called by the LeafNFT contract /// @dev This function may grow new branch if current branch is full. /// @dev Do not use manually except for maintenance purpose. /// @param genesisBranch BranchID of the genesis branch /// @param tokenID LookRevLeafNFT ERC721 token ID /// @return uint256 updated average leaf cost function addLeafToOpenBranch(uint256 genesisBranch, uint256 tokenID) external override returns (uint256) { require(msg.sender == admin || msg.sender == lrLeaf, "LookRevTree: Not authorized"); _addLeafToOpenBranch(genesisBranch, tokenID); return _getAverageLeafCost(); } function _addLeafToOpenBranch(uint256 genesisBranch, uint256 tokenID) internal { require(genesisBranch > 0, "LookRevTree: Branch index is out of range"); if (genesisBranch >= nextGenesisBranchId) { genesisBranch = nextGenesisBranchId - 1; } require(genesisBranches[genesisBranch].state == 0, "LookRevTree: Branch is not OPEN"); uint256 _b = genesisBranches[genesisBranch].openBranch; if (branches[_b].availableLeaves < 1) { _updateBranchStatus(_b); } _addLeaf(genesisBranches[genesisBranch].openBranch, tokenID); emit AddedLeaves(genesisBranch, nextLeafId - 1, tokenID, 1); } /// @dev Get branch that has minimum leaves, for the balance of the tree function _getMinLeavesBranch() internal view returns (uint256) { uint256 minCount = 10000; uint256 b = nextBranchId - 1; for (uint256 i = 1; i < nextGenesisBranchId; i++) { if (genesisBranches[i].state == 0 && genesisBranches[i].leavesCount < minCount) { minCount = genesisBranches[i].leavesCount; b = genesisBranches[i].openBranch; } } return b; } /// @dev Add leaves on open branches, growing a balanced tree /// Can add multiple leaves. /// @dev This function is going to add new leaves on the open branches on the tree /// @dev Do not use manually except for maintenance purpose. /// @param tokenIDs to add to the branches function addLeavesToOpenBranches(uint256[] calldata tokenIDs) external override returns (uint256) { require(msg.sender == admin || msg.sender == lrLeaf, "LookRevTree: Not authorized."); require(tokenIDs.length > 0, "LookRevTree: tokenIDs can not be empty"); require(tokenIDToLeafID[tokenIDs[0]] == 0, "LookRevTree: TokenID already registered"); uint256 _branchid = _getMinLeavesBranch(); for (uint256 i = 0; i < tokenIDs.length; i++) { if (branches[_branchid].availableLeaves < 1) { _updateBranchStatus(_branchid); _branchid = _getMinLeavesBranch(); } _addLeaf(_branchid, tokenIDs[i]); } emit AddedLeaves(_branchid, nextLeafId - 1, tokenIDs[0], tokenIDs.length); return _getAverageLeafCost(); } /// @dev Called internally. Precheck to ensure the branch is open and available for new leaves /// @param branch BranchID of the subbranch /// @param tokenID of the added leaf function _addLeaf(uint256 branch, uint256 tokenID) internal { require(treeStatus == 0, "LookRevTree: Tree is currently not OPEN."); require(branch < nextBranchId && branch > 0, "LookRevTree: Branch index is out of range"); require(tokenIDToLeafID[tokenID] == 0, "LookRevTree: TokenID already registered"); /// prevent reentry tokenIDToLeafID[tokenID] = nextLeafId; leaves[nextLeafId] = Leaf(nextLeafId, branch, tokenID, block.timestamp); genesisBranches[branches[branch].genesisBranch].leavesCount += 1; branches[branch].availableLeaves -= 1; nextLeafId += 1; } /// @dev update the subbranch status, usually when the subbranch is full function _updateBranchStatus(uint256 subbranch) internal { uint256 _g = branches[subbranch].genesisBranch; if (genesisBranches[_g].leavesCount >= HARVEST_START_COUNT) { _setFirstHarvestTime(_g); } _createBranch(_g); genesisBranches[_g].openBranch = nextBranchId - 1; } ///================================= /// Methods for leaf owners ///================================= function getTokenPubID(uint256 tokenID) external view override returns (string memory) { address _owner = LookRevLeafNFT(lrLeaf).getNFTTokenRecipient(tokenID); require(_owner == msg.sender || msg.sender == admin, "LookRevTree: Require owner of the leafNFT"); return tokenIDToPubID[tokenID]; } /// @dev PubID can only be updated before leaf migration and is preserved with the tree function updateNFTTokenPubID(uint256 tokenID, string calldata pubID) external override { require(tokenIDToLeafID[tokenID] > 0, "LookRevTree: tokenID not found"); require(bytes(pubID).length > 0, "LookRevTree: pubID can not be empty"); address _owner = LookRevLeafNFT(lrLeaf).getNFTTokenRecipient(tokenID); require(_owner == msg.sender || msg.sender == admin, "LookRevTree: Require owner of the leafNFT"); tokenIDToPubID[tokenID] = pubID; } function updateNFTTokenPubIDs(uint256[] calldata tokenIDs, string[] calldata pubIDs) public { require(msg.sender == admin, "LookRevTree: Require admin"); for (uint256 i = 0; i < tokenIDs.length; i++) { tokenIDToPubID[tokenIDs[i]] = pubIDs[i]; } } ///========================================== /// Maintenance methods for branch operators ///========================================== /// Set the first harvest time for a genesis branch /// @dev The first harvest time is 100 days after the current block time /// @param branch branchID of the genesis branch function _setFirstHarvestTime(uint256 branch) internal { if (genesisBranches[branch].harvestTime != 0) { // already set the first harvest time return; } genesisBranches[branch].harvestTime = block.timestamp + FIRST_HARVEST_TIME; emit HarvestTimeScheduled(branch, genesisBranches[branch].openBranch, genesisBranches[branch].leavesCount, genesisBranches[branch].harvestTime); } /// Update genesis branch information /// @param branch BranchID of the genesis branch /// @param newName New name of the genesis branch /// @param newURI New uri of the genesis branch /// @param newState New state of the genesis branch 0 = OPEN, 1 = PAUSE, 2 = STOP /// @param timeToHarvest Havest time adjusted with delay from the current block time /// Require admin or branch operator function updateBranchInfo(uint256 branch, string calldata newName, string calldata newURI, uint8 newState, uint256 timeToHarvest) public { require(msg.sender == admin || operators[branch][msg.sender] == true, "LookRevTree: Not authorized"); require(branch < nextGenesisBranchId && branch > 0, "LookRevTree: Branch index is out of range"); genesisBranches[branch].name = newName; genesisBranches[branch].uri = newURI; genesisBranches[branch].state = newState; genesisBranches[branch].harvestTime = block.timestamp + timeToHarvest; } ///=============================== /// Maintenance methods for admin ///=============================== function updateTreeStatus(string calldata str, uint8 _to) public { require(msg.sender == admin, "LookRevTree: Not authorized"); statusInfo = str; treeStatus = _to; } /// Add or remove operator for a genesis branch function updateOperator(uint256[] calldata branch, address operator, bool approved) public { require(msg.sender == admin, "LookRevTree: Not authorized"); require(operator != address(0), "LookRevTree: operator needs valid address"); for (uint256 i = 0; i < branch.length; i++) { operators[branch[i]][operator] = approved; } emit OperatorUpdated(branch[0], operator, approved); } /// Adjust base value /// @dev Can only increase base value of leaf when it is out of sync from market value /// @dev Need to wait at least 100 days between updates /// @param value updated baseValue for new genesis branches function adjustBaseValue(uint256 value) public { require(msg.sender == admin, "LookRevTree: Not authorized"); require(value > MIN_BASE_VALUE, "LookRevTree: Can only increase base value"); require(block.timestamp >= START_TIME + 100 days, "LooksCoin: Wait for 100 days after last update"); MIN_BASE_VALUE = value; START_TIME = block.timestamp; } function updateLeafVersion(address _leaf) public { require(msg.sender == admin, "LookRevTree: Not authorized"); lrLeaf = _leaf; leafVersions.push(_leaf); emit VersionUpdated("Leaf Version Updated", _leaf); } function getLeafVersions() public view returns (address[] memory) { require(msg.sender == admin, "LookRevTree: Not authorized"); return leafVersions; } function updateNextContract(address _new) public { require(msg.sender == admin, "LookRevTree: Not authorized"); nextTree = _new; } function updateRole(uint256 _role, address _new) public { require(msg.sender == admin || msg.sender == ceo || msg.sender == cfo, "LookRevTree: Not authorized"); if (_role == 1) { admin = _new; emit RoleUpdated("admin", _new); } else if (_role == 2) { ceo = _new; emit RoleUpdated("ceo", _new); } else if (_role == 3) { cfo = _new; emit RoleUpdated("cfo", _new); } } function getRoles() public view returns (address[] memory) { require(msg.sender == admin || msg.sender == ceo || msg.sender == cfo, "LookRevTree: Not authorized"); address[] memory _roles = new address[](3); _roles[0] = admin; _roles[1] = ceo; _roles[2] = cfo; return _roles; } function removeLeaf(uint256 leafID) public { require(msg.sender == admin, "LookRevTree: Not authorized"); _removeLeaf(leafID); } /// @dev PubID is preserved with the tree since it is not affected by migration function _removeLeaf(uint256 leafID) internal { if (leafID <= 0 || leafID >= nextLeafId) { return; } uint256 _tokenID = leaves[leafID].tokenID; if (_tokenID < 1) { return; } tokenIDToLeafID[_tokenID] = 0; delete leaves[leafID]; } function migrateNFTTokens(uint256 newBranchID, uint256[] calldata tokenIDs) external { require(msg.sender == admin, "LookRevTree: Not authorized"); require(nextTree != address(0), "LookRevTree: Need to set nextTree"); for (uint256 i = 0; i < tokenIDs.length; i++) { if (tokenIDs[i] > 0) { _removeLeaf(tokenIDToLeafID[tokenIDs[i]]); } } INextTree(nextTree).migrateTokens(newBranchID, tokenIDs, lrLeaf); } }
Creating a branch from the genesis branch @param branch BranchID of the genesis branch
function _createBranch(uint256 branch) internal { require(genesisBranches[branch].state == 0, "LookRevTree: Branch is not OPEN"); uint256 _maxLevel = genesisBranches[branch].maxLevel; uint256 _count = branchesAtLevel[branch][_maxLevel].length; if (_count < _maxLevel * BRANCH_UNIT) { _createNewBranch(branch, _maxLevel); genesisBranches[branch].maxLevel += 1; _createNewBranch(branch, _maxLevel + 1); } }
10,912,922
[ 1, 11092, 279, 3803, 628, 326, 21906, 3803, 225, 3803, 15449, 734, 434, 326, 21906, 3803, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2640, 7108, 12, 11890, 5034, 3803, 13, 2713, 288, 203, 3639, 2583, 12, 4507, 16786, 24246, 63, 7500, 8009, 2019, 422, 374, 16, 315, 9794, 10070, 2471, 30, 15449, 353, 486, 11919, 8863, 203, 3639, 2254, 5034, 389, 1896, 2355, 273, 21906, 24246, 63, 7500, 8009, 1896, 2355, 31, 203, 3639, 2254, 5034, 389, 1883, 273, 11483, 861, 2355, 63, 7500, 6362, 67, 1896, 2355, 8009, 2469, 31, 203, 3639, 309, 261, 67, 1883, 411, 389, 1896, 2355, 380, 22427, 20360, 67, 15736, 13, 288, 203, 5411, 389, 2640, 1908, 7108, 12, 7500, 16, 389, 1896, 2355, 1769, 203, 5411, 21906, 24246, 63, 7500, 8009, 1896, 2355, 1011, 404, 31, 203, 5411, 389, 2640, 1908, 7108, 12, 7500, 16, 389, 1896, 2355, 397, 404, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xb397fc77aC18DDD3Ead391a3Ca64892817De881C/sources/browser/flatten.sol
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral in order to account for precision loss. @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. @return amountWithdrawn The actual amount of collateral withdrawn./ If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. Decrease the sponsors position size of collateral and tokens. Decrease the contract's collateral and tokens.
function redeem(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.requestPassTimestamp == 0); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul( _getCollateral(positionData.rawCollateral) ); if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); _removeCollateral(positionData.rawCollateral, collateralRedeemed); FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, collateralRedeemed); totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); }
16,255,917
[ 1, 38, 321, 87, 1375, 2107, 5157, 68, 434, 1375, 2316, 7623, 68, 471, 9573, 1473, 326, 23279, 287, 3844, 434, 1375, 12910, 2045, 287, 7623, 8338, 225, 4480, 1338, 506, 2566, 635, 279, 1147, 272, 500, 2467, 18, 490, 750, 486, 283, 24903, 326, 1983, 23279, 287, 3844, 434, 4508, 2045, 287, 316, 1353, 358, 2236, 364, 6039, 8324, 18, 225, 818, 5157, 353, 326, 1300, 434, 2430, 358, 506, 18305, 88, 364, 279, 1543, 773, 295, 340, 3844, 434, 4508, 2045, 287, 18, 327, 3844, 1190, 9446, 82, 1021, 3214, 3844, 434, 4508, 2045, 287, 598, 9446, 82, 18, 19, 971, 283, 19117, 375, 1135, 777, 2430, 326, 272, 500, 2467, 711, 1508, 732, 848, 1430, 3675, 1754, 18, 16289, 16, 2588, 1467, 18, 31073, 448, 326, 272, 500, 87, 1383, 1754, 963, 434, 4508, 2045, 287, 471, 2430, 18, 31073, 448, 326, 6835, 1807, 4508, 2045, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 283, 24903, 12, 7505, 2148, 18, 13290, 3778, 818, 5157, 13, 203, 3639, 1071, 203, 3639, 1338, 1386, 12028, 1435, 203, 3639, 1656, 281, 1435, 203, 3639, 1135, 261, 7505, 2148, 18, 13290, 3778, 3844, 1190, 9446, 82, 13, 203, 565, 288, 203, 3639, 11010, 751, 2502, 1754, 751, 273, 389, 588, 2555, 751, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 3276, 751, 18, 2293, 6433, 4921, 422, 374, 1769, 203, 3639, 2583, 12, 5, 2107, 5157, 18, 291, 28130, 12, 3276, 751, 18, 7860, 1182, 15167, 10019, 203, 203, 3639, 15038, 2148, 18, 13290, 3778, 8330, 426, 24903, 329, 273, 818, 5157, 18, 2892, 12, 3276, 751, 18, 7860, 1182, 15167, 1769, 203, 3639, 15038, 2148, 18, 13290, 3778, 4508, 2045, 287, 426, 24903, 329, 273, 8330, 426, 24903, 329, 18, 16411, 12, 203, 5411, 389, 588, 13535, 2045, 287, 12, 3276, 751, 18, 1899, 13535, 2045, 287, 13, 203, 3639, 11272, 203, 203, 3639, 309, 261, 3276, 751, 18, 7860, 1182, 15167, 18, 291, 5812, 12, 2107, 5157, 3719, 288, 203, 5411, 3844, 1190, 9446, 82, 273, 389, 3733, 55, 500, 2467, 2555, 12, 3576, 18, 15330, 1769, 203, 5411, 389, 4479, 13535, 2045, 287, 12, 3276, 751, 18, 1899, 13535, 2045, 287, 16, 4508, 2045, 287, 426, 24903, 329, 1769, 203, 5411, 15038, 2148, 18, 13290, 3778, 394, 1345, 1380, 273, 1754, 751, 18, 7860, 1182, 15167, 18, 1717, 12, 2107, 5157, 1769, 203, 5411, 2583, 12, 2704, 1345, 1380, 18, 291, 28130, 22376, 12, 1154, 55, 2 ]
pragma solidity ^0.4.18; /** * @title SafeMath for performing valid mathematics. */ library SafeMath { function Mul(uint a, uint b) internal pure returns (uint) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function Div(uint a, uint b) internal pure returns (uint) { //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(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function Add(uint a, uint b) internal pure returns (uint) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public; } /** * Contract "Ownable" * Purpose: Defines Owner for contract and provide functionality to transfer ownership to another account */ contract Ownable { //owner variable to store contract owner account address public owner; //add another owner to transfer ownership address oldOwner; //Constructor for the contract to store owner's account on deployement function Ownable() public { owner = msg.sender; oldOwner = msg.sender; } //modifier to check transaction initiator is only owner modifier onlyOwner() { require (msg.sender == owner || msg.sender == oldOwner); _; } //ownership can be transferred to provided newOwner. Function can only be initiated by contract owner's account function transferOwnership(address newOwner) public onlyOwner { require (newOwner != address(0)); owner = newOwner; } } /** * @title ERC20 interface */ contract ERC20 is Ownable { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 value); function transfer(address _to, uint256 _value) public returns (bool _success); function allowance(address owner, address spender) public view returns (uint256 _value); function transferFrom(address from, address to, uint256 value) public returns (bool _success); function approve(address spender, uint256 value) public returns (bool _success); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed _from, address indexed _to, uint _value, bytes comment); } contract CTV is ERC20 { using SafeMath for uint256; //The name of the token string public constant name = "Coin TV"; //The token symbol string public constant symbol = "CTV"; //To denote the locking on transfer of tokens among token holders bool public locked; //The precision used in the calculations in contract uint8 public constant decimals = 18; //maximum number of tokens uint256 constant MAXCAP = 29999990e18; // maximum number of tokens that can be supplied by referrals uint public constant MAX_REFERRAL_TOKENS = 2999999e18; //set the softcap of ether received uint256 constant SOFTCAP = 70 ether; //Refund eligible or not // 0: sale not started yet, refunding invalid // 1: refund not required // 2: softcap not reached, refund required // 3: Refund in progress // 4: Everyone refunded uint256 public refundStatus = 0; //the account which will receive all balance address ethCollector; //to save total number of ethers received uint256 totalWeiReceived; //count tokens earned by referrals uint256 public tokensSuppliedFromReferral = 0; //Mapping to relate owner and spender to the tokens allowed to transfer from owner mapping(address => mapping(address => uint256)) allowed; //to manage referrals mapping(address => address) public referredBy; //Mapping to relate number of token to the account mapping(address => uint256) balances; //Structure for investors; holds received wei amount and Token sent struct Investor { //wei received during PreSale uint weiReceived; //Tokens sent during CrowdSale uint tokensPurchased; //user has been refunded or not bool refunded; //Uniquely identify an investor(used for iterating) uint investorID; } //time when the sale starts uint256 public startTime; //time when the presale ends uint256 public endTime; //to check the sale status bool public saleRunning; //investors indexed by their ETH address mapping(address => Investor) public investors; //investors indexed by their IDs mapping (uint256 => address) public investorList; //count number of investors uint256 public countTotalInvestors; //to keep track of how many investors have been refunded uint256 countInvestorsRefunded; //by default any new account will show false for registered mapping mapping(address => bool) registered; address[] listOfAddresses; //events event StateChanged(bool); function CTV() public{ totalSupply = 0; startTime = 0; endTime = 0; saleRunning = false; locked = true; setEthCollector(0xAf3BBf663769De9eEb6C2b235262Cf704eD4EA4b); } //To handle ERC20 short address attack modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } modifier onlyUnlocked() { require (!locked); _; } modifier validTimeframe(){ require(saleRunning && now >=startTime && now < endTime); _; } function setEthCollector(address _ethCollector) public onlyOwner{ require(_ethCollector != address(0)); ethCollector = _ethCollector; } function startSale() public onlyOwner{ require(startTime == 0); startTime = now; endTime = startTime.Add(7 weeks); saleRunning = true; } //To enable transfer of tokens function unlockTransfer() external onlyOwner{ locked = false; } /** * @dev Check if the address being passed belongs to a contract * * @param _address The address which you want to verify * @return A bool specifying if the address is that of contract or not */ function isContract(address _address) private view returns(bool _isContract){ assert(_address != address(0) ); uint length; //inline assembly code to check the length of address assembly{ length := extcodesize(_address) } if(length > 0){ return true; } else{ return false; } } /** * @dev Check balance of given account address * * @param _owner The address account whose balance you want to know * @return balance of the account */ function balanceOf(address _owner) public view returns (uint256 _value){ return balances[_owner]; } /** * @dev Transfer sender's token to a given address * * @param _to The address which you want to transfer to * @param _value the amount of tokens to be transferred * @return A bool if the transfer was a success or not */ function transfer(address _to, uint _value) onlyUnlocked onlyPayloadSize(2 * 32) public returns(bool _success) { require( _to != address(0) ); bytes memory _empty; if((balances[msg.sender] > _value) && _value > 0 && _to != address(0)){ balances[msg.sender] = balances[msg.sender].Sub(_value); balances[_to] = balances[_to].Add(_value); if(isContract(_to)){ ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _empty); } Transfer(msg.sender, _to, _value, _empty); return true; } else{ return false; } } /** * @dev Transfer tokens to an address given by sender. To make ERC223 compliant * * @param _to The address which you want to transfer to * @param _value the amount of tokens to be transferred * @param _data additional information of account from where to transfer from * @return A bool if the transfer was a success or not */ function transfer(address _to, uint _value, bytes _data) onlyUnlocked onlyPayloadSize(3 * 32) public returns(bool _success) { if((balances[msg.sender] > _value) && _value > 0 && _to != address(0)){ balances[msg.sender] = balances[msg.sender].Sub(_value); balances[_to] = balances[_to].Add(_value); if(isContract(_to)){ ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } else{ return false; } } /** * @dev Transfer tokens from one address to another, for ERC20. * * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value the amount of tokens to be transferred * @return A bool if the transfer was a success or not */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3*32) public onlyUnlocked returns (bool){ bytes memory _empty; if((_value > 0) && (_to != address(0)) && (_from != address(0)) && (allowed[_from][msg.sender] > _value )){ balances[_from] = balances[_from].Sub(_value); balances[_to] = balances[_to].Add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].Sub(_value); if(isContract(_to)){ ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _empty); } Transfer(_from, _to, _value, _empty); return true; } else{ return false; } } /** * @dev Function to check the amount of tokens that an owner has allowed a spender to recieve from owner. * * @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 to spend. */ function allowance(address _owner, address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool){ if( (_value > 0) && (_spender != address(0)) && (balances[msg.sender] >= _value)){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } else{ return false; } } /** * @dev Calculate number of tokens that will be received in one ether * */ function getPrice() public view returns(uint256) { uint256 price; if(totalSupply <= 1e6*1e18) price = 13330; else if(totalSupply <= 5e6*1e18) price = 12500; else if(totalSupply <= 9e6*1e18) price = 11760; else if(totalSupply <= 13e6*1e18) price = 11110; else if(totalSupply <= 17e6*1e18) price = 10520; else if(totalSupply <= 21e6*1e18) price = 10000; else{ //zero indicates that no tokens will be allocated when total supply //of 21 million tokens is reached price = 0; } return price; } function mintAndTransfer(address beneficiary, uint256 numberOfTokensWithoutDecimal, bytes comment) public onlyOwner { uint256 tokensToBeTransferred = numberOfTokensWithoutDecimal*1e18; require(totalSupply.Add(tokensToBeTransferred) <= MAXCAP); totalSupply = totalSupply.Add(tokensToBeTransferred); balances[beneficiary] = balances[beneficiary].Add(tokensToBeTransferred); Transfer(owner, beneficiary ,tokensToBeTransferred, comment); } /** * @dev to enable pause sale for break in ICO and Pre-ICO * */ function pauseSale() public onlyOwner{ assert(saleRunning && startTime > 0 && now <= endTime); saleRunning = false; } /** * @dev to resume paused sale * */ function resumeSale() public onlyOwner{ assert(!saleRunning && startTime > 0 && now <= endTime); saleRunning = true; } function buyTokens(address beneficiary) internal validTimeframe { uint256 tokensBought = msg.value.Mul(getPrice()); balances[beneficiary] = balances[beneficiary].Add(tokensBought); totalSupply = totalSupply.Add(tokensBought); //Make entry in Investor indexed with address Investor storage investorStruct = investors[beneficiary]; //If it is a new investor, then create a new id if(investorStruct.investorID == 0){ countTotalInvestors++; investorStruct.investorID = countTotalInvestors; investorList[countTotalInvestors] = beneficiary; } else{ investorStruct.weiReceived = investorStruct.weiReceived.Add(msg.value); investorStruct.tokensPurchased = investorStruct.tokensPurchased.Add(tokensBought); } //Award referral tokens if(referredBy[msg.sender] != address(0)){ //give some referral tokens balances[referredBy[msg.sender]] = balances[referredBy[msg.sender]].Add(tokensBought/10); tokensSuppliedFromReferral = tokensSuppliedFromReferral.Add(tokensBought/10); totalSupply = totalSupply.Add(tokensBought/10); } //if referrer was also referred by someone if(referredBy[referredBy[msg.sender]] != address(0)){ //give 1% tokens to 2nd generation referrer balances[referredBy[referredBy[msg.sender]]] = balances[referredBy[referredBy[msg.sender]]].Add(tokensBought/100); if(tokensSuppliedFromReferral.Add(tokensBought/100) < MAX_REFERRAL_TOKENS) tokensSuppliedFromReferral = tokensSuppliedFromReferral.Add(tokensBought/100); totalSupply = totalSupply.Add(tokensBought/100); } assert(totalSupply <= MAXCAP); totalWeiReceived = totalWeiReceived.Add(msg.value); ethCollector.transfer(msg.value); } /** * @dev This function is used to register a referral. * Whoever calls this function, is telling contract, * that "I was referred by referredByAddress" * Whenever I am going to buy tokens, 10% will be awarded to referredByAddress * * @param referredByAddress The address of person who referred the person calling this function */ function registerReferral (address referredByAddress) public { require(msg.sender != referredByAddress && referredByAddress != address(0)); referredBy[msg.sender] = referredByAddress; } /** * @dev Owner is allowed to manually register who was referred by whom * @param heWasReferred The address of person who was referred * @param I_referred_this_person The person who referred the above address */ function referralRegistration(address heWasReferred, address I_referred_this_person) public onlyOwner { require(heWasReferred != address(0) && I_referred_this_person != address(0)); referredBy[heWasReferred] = I_referred_this_person; } /** * Finalize the crowdsale */ function finalize() public onlyOwner { //Make sure Sale is running assert(saleRunning); if(MAXCAP.Sub(totalSupply) <= 1 ether || now > endTime){ //now sale can be finished saleRunning = false; } //Refund eligible or not // 0: sale not started yet, refunding invalid // 1: refund not required // 2: softcap not reached, refund required // 3: Refund in progress // 4: Everyone refunded //Checks if the fundraising goal is reached in crowdsale or not if (totalWeiReceived < SOFTCAP) refundStatus = 2; else refundStatus = 1; //crowdsale is ended saleRunning = false; //enable transferring of tokens among token holders locked = false; //Emit event when crowdsale state changes StateChanged(true); } /** * Refund the investors in case target of crowdsale not achieved */ function refund() public onlyOwner { assert(refundStatus == 2 || refundStatus == 3); uint batchSize = countInvestorsRefunded.Add(30) < countTotalInvestors ? countInvestorsRefunded.Add(30): countTotalInvestors; for(uint i=countInvestorsRefunded.Add(1); i <= batchSize; i++){ address investorAddress = investorList[i]; Investor storage investorStruct = investors[investorAddress]; //If purchase has been made during CrowdSale if(investorStruct.tokensPurchased > 0 && investorStruct.tokensPurchased <= balances[investorAddress]){ //return everything investorAddress.transfer(investorStruct.weiReceived); //Reduce totalWeiReceived totalWeiReceived = totalWeiReceived.Sub(investorStruct.weiReceived); //Update totalSupply totalSupply = totalSupply.Sub(investorStruct.tokensPurchased); // reduce balances balances[investorAddress] = balances[investorAddress].Sub(investorStruct.tokensPurchased); //set everything to zero after transfer successful investorStruct.weiReceived = 0; investorStruct.tokensPurchased = 0; investorStruct.refunded = true; } } //Update the number of investors that have recieved refund countInvestorsRefunded = batchSize; if(countInvestorsRefunded == countTotalInvestors){ refundStatus = 4; } StateChanged(true); } function extendSale(uint56 numberOfDays) public onlyOwner{ saleRunning = true; endTime = now.Add(numberOfDays*86400); StateChanged(true); } /** * @dev This will receive ether from owner so that the contract has balance while refunding * */ function prepareForRefund() public payable {} function () public payable { buyTokens(msg.sender); } /** * Failsafe drain */ function drain() public onlyOwner { owner.transfer(this.balance); } }
* @dev Owner is allowed to manually register who was referred by whom @param heWasReferred The address of person who was referred @param I_referred_this_person The person who referred the above address/
function referralRegistration(address heWasReferred, address I_referred_this_person) public onlyOwner { require(heWasReferred != address(0) && I_referred_this_person != address(0)); referredBy[heWasReferred] = I_referred_this_person; }
1,781,027
[ 1, 5541, 353, 2935, 358, 10036, 1744, 10354, 1703, 29230, 635, 600, 362, 225, 3904, 14992, 426, 4193, 1021, 1758, 434, 6175, 10354, 1703, 29230, 225, 467, 67, 266, 4193, 67, 2211, 67, 12479, 1021, 6175, 10354, 29230, 326, 5721, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1278, 29084, 7843, 12, 2867, 3904, 14992, 426, 4193, 16, 1758, 467, 67, 266, 4193, 67, 2211, 67, 12479, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 580, 14992, 426, 4193, 480, 1758, 12, 20, 13, 597, 467, 67, 266, 4193, 67, 2211, 67, 12479, 480, 1758, 12, 20, 10019, 203, 3639, 29230, 858, 63, 580, 14992, 426, 4193, 65, 273, 467, 67, 266, 4193, 67, 2211, 67, 12479, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../interfaces/ICLeverCVXLocker.sol"; import "../interfaces/ICLeverToken.sol"; import "../interfaces/IConvexCVXLocker.sol"; import "../interfaces/IConvexCVXRewardPool.sol"; import "../interfaces/IFurnace.sol"; import "../interfaces/ISnapshotDelegateRegistry.sol"; import "../interfaces/IZap.sol"; // solhint-disable not-rely-on-time, max-states-count, reason-string contract CLeverCVXLocker is OwnableUpgradeable, ICLeverCVXLocker { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; event UpdateWhitelist(address indexed _whitelist, bool _status); event UpdateStakePercentage(uint256 _percentage); event UpdateStakeThreshold(uint256 _threshold); event UpdateRepayFeePercentage(uint256 _feePercentage); event UpdatePlatformFeePercentage(uint256 _feePercentage); event UpdateHarvestBountyPercentage(uint256 _percentage); event UpdatePlatform(address indexed _platform); event UpdateZap(address indexed _zap); event UpdateGovernor(address indexed _governor); // The precision used to calculate accumulated rewards. uint256 private constant PRECISION = 1e18; // The denominator used for fee calculation. uint256 private constant FEE_DENOMINATOR = 1e9; // The maximum value of repay fee percentage. uint256 private constant MAX_REPAY_FEE = 1e8; // 10% // The maximum value of platform fee percentage. uint256 private constant MAX_PLATFORM_FEE = 2e8; // 20% // The maximum value of harvest bounty percentage. uint256 private constant MAX_HARVEST_BOUNTY = 1e8; // 10% // The length of epoch in CVX Locker. uint256 private constant REWARDS_DURATION = 86400 * 7; // 1 week // The address of CVX token. address private constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; // The address of cvxCRV token. address private constant CVXCRV = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7; // The address of CVXRewardPool Contract. address private constant CVX_REWARD_POOL = 0xCF50b810E57Ac33B91dCF525C6ddd9881B139332; // The address of CVXLockerV2 Contract. address private constant CVX_LOCKER = 0x72a19342e8F1838460eBFCCEf09F6585e32db86E; // The address of votium distributor address private constant VOTIUM_DISTRIBUTOR = 0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A; struct EpochUnlockInfo { // The number of CVX should unlocked at the start of epoch `unlockEpoch`. uint192 pendingUnlock; // The epoch number to unlock `pendingUnlock` CVX uint64 unlockEpoch; } struct UserInfo { // The total number of clevCVX minted. uint128 totalDebt; // The amount of distributed reward. uint128 rewards; // The paid accumulated reward per share, multipled by 1e18. uint192 rewardPerSharePaid; // The block number of the last interacted block (deposit, unlock, withdraw, repay, borrow). uint64 lastInteractedBlock; // The total amount of CVX locked. uint112 totalLocked; // The total amount of CVX unlocked. uint112 totalUnlocked; // The next unlock index to speedup unlock process. uint32 nextUnlockIndex; // In Convex, if you lock at epoch `e` (block.timestamp in `[e * rewardsDuration, (e + 1) * rewardsDuration)`), // you lock will start at epoch `e + 1` and will unlock at the beginning of epoch `(e + 17)`. If we relock right // after the unlock, all unlocked CVX will start lock at epoch `e + 18`, and will locked again at epoch `e + 18 + 16`. // If we continue the process, all CVX locked in epoch `e` will be unlocked at epoch `e + 17 * k` (k >= 1). // // Here, we maintain an array for easy calculation when users lock or unlock. // // `epochLocked[r]` maintains all locked CVX whose unlocking epoch is `17 * k + r`. It means at the beginning of // epoch `17 * k + r`, the CVX will unlock, if we continue to relock right after unlock. uint256[17] epochLocked; // The list of pending unlocked CVX. EpochUnlockInfo[] pendingUnlockList; } /// @dev The address of governor address public governor; /// @dev The address of clevCVX contract. address public clevCVX; /// @dev Assumptons: /// 1. totalLockedGlobal + totalPendingUnlockGlobal is the total amount of CVX locked in CVXLockerV2. /// 2. totalUnlockedGlobal is the total amount of CVX unlocked from CVXLockerV2 but still in contract. /// 3. totalDebtGlobal is the total amount of clevCVX borrowed, will decrease when debt is repayed. /// @dev The total amount of CVX locked in contract. uint256 public totalLockedGlobal; /// @dev The total amount of CVX going to unlocked. uint256 public totalPendingUnlockGlobal; /// @dev The total amount of CVX unlocked in CVXLockerV2 and will never be locked again. uint256 public totalUnlockedGlobal; /// @dev The total amount of clevCVX borrowed from this contract. uint256 public totalDebtGlobal; /// @dev The reward per share of CVX accumulated, will be updated in each harvest, multipled by 1e18. uint256 public accRewardPerShare; /// @dev Mapping from user address to user info. mapping(address => UserInfo) public userInfo; /// @dev Mapping from epoch number to the amount of CVX to be unlocked. mapping(uint256 => uint256) public pendingUnlocked; /// @dev The address of Furnace Contract. address public furnace; /// @dev The percentage of free CVX will be staked in CVXRewardPool. uint256 public stakePercentage; /// @dev The minimum of amount of CVX to be staked. uint256 public stakeThreshold; /// @dev The debt reserve rate to borrow clevCVX for each user. uint256 public reserveRate; /// @dev The list of tokens which will swap manually. mapping(address => bool) public manualSwapRewardToken; /// @dev The address of zap contract. address public zap; /// @dev The percentage of repay fee. uint256 public repayFeePercentage; /// @dev The percentage of rewards to take for caller on harvest uint256 public harvestBountyPercentage; /// @dev The percentage of rewards to take for platform on harvest uint256 public platformFeePercentage; /// @dev The address of recipient of platform fee address public platform; /// @dev The list of whitelist keeper. mapping(address => bool) public isKeeper; modifier onlyGovernorOrOwner() { require(msg.sender == governor || msg.sender == owner(), "CLeverCVXLocker: only governor or owner"); _; } modifier onlyKeeper() { require(isKeeper[msg.sender], "CLeverCVXLocker: only keeper"); _; } function initialize( address _governor, address _clevCVX, address _zap, address _furnace, address _platform, uint256 _platformFeePercentage, uint256 _harvestBountyPercentage ) external initializer { OwnableUpgradeable.__Ownable_init(); require(_governor != address(0), "CLeverCVXLocker: zero governor address"); require(_clevCVX != address(0), "CLeverCVXLocker: zero clevCVX address"); require(_zap != address(0), "CLeverCVXLocker: zero zap address"); require(_furnace != address(0), "CLeverCVXLocker: zero furnace address"); require(_platform != address(0), "CLeverCVXLocker: zero platform address"); require(_platformFeePercentage <= MAX_PLATFORM_FEE, "CLeverCVXLocker: fee too large"); require(_harvestBountyPercentage <= MAX_HARVEST_BOUNTY, "CLeverCVXLocker: fee too large"); governor = _governor; clevCVX = _clevCVX; zap = _zap; furnace = _furnace; platform = _platform; platformFeePercentage = _platformFeePercentage; harvestBountyPercentage = _harvestBountyPercentage; reserveRate = 500_000_000; } /********************************** View Functions **********************************/ /// @dev Return user info in this contract. /// @param _account The address of user. /// @return totalDeposited The amount of CVX deposited in this contract of the user. /// @return totalPendingUnlocked The amount of CVX pending to be unlocked. /// @return totalUnlocked The amount of CVX unlokced of the user and can be withdrawed. /// @return totalBorrowed The amount of clevCVX borrowed by the user. /// @return totalReward The amount of CVX reward accrued for the user. function getUserInfo(address _account) external view override returns ( uint256 totalDeposited, uint256 totalPendingUnlocked, uint256 totalUnlocked, uint256 totalBorrowed, uint256 totalReward ) { UserInfo storage _info = userInfo[_account]; totalDeposited = _info.totalLocked; // update total reward and total Borrowed totalBorrowed = _info.totalDebt; totalReward = uint256(_info.rewards).add( accRewardPerShare.sub(_info.rewardPerSharePaid).mul(totalDeposited) / PRECISION ); if (totalBorrowed > 0) { if (totalReward >= totalBorrowed) { totalReward -= totalBorrowed; totalBorrowed = 0; } else { totalBorrowed -= totalReward; totalReward = 0; } } // update total unlocked and total pending unlocked. totalUnlocked = _info.totalUnlocked; EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList; uint256 _nextUnlockIndex = _info.nextUnlockIndex; uint256 _currentEpoch = block.timestamp / REWARDS_DURATION; while (_nextUnlockIndex < _pendingUnlockList.length) { if (_pendingUnlockList[_nextUnlockIndex].unlockEpoch <= _currentEpoch) { totalUnlocked += _pendingUnlockList[_nextUnlockIndex].pendingUnlock; } else { totalPendingUnlocked += _pendingUnlockList[_nextUnlockIndex].pendingUnlock; } _nextUnlockIndex += 1; } } /// @dev Return the lock and pending unlocked list of user. /// @param _account The address of user. /// @return locks The list of CVX locked by the user, including amount and nearest unlock epoch. /// @return pendingUnlocks The list of CVX pending unlocked of the user, including amount and the unlock epoch. function getUserLocks(address _account) external view returns (EpochUnlockInfo[] memory locks, EpochUnlockInfo[] memory pendingUnlocks) { UserInfo storage _info = userInfo[_account]; uint256 _currentEpoch = block.timestamp / REWARDS_DURATION; uint256 lengthLocks; for (uint256 i = 0; i < 17; i++) { if (_info.epochLocked[i] > 0) { lengthLocks++; } } locks = new EpochUnlockInfo[](lengthLocks); lengthLocks = 0; for (uint256 i = 0; i < 17; i++) { uint256 _index = (_currentEpoch + i + 1) % 17; if (_info.epochLocked[_index] > 0) { locks[lengthLocks].pendingUnlock = uint192(_info.epochLocked[_index]); locks[lengthLocks].unlockEpoch = uint64(_currentEpoch + i + 1); lengthLocks += 1; } } uint256 _nextUnlockIndex = _info.nextUnlockIndex; EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList; uint256 lengthPendingUnlocks; for (uint256 i = _nextUnlockIndex; i < _pendingUnlockList.length; i++) { if (_pendingUnlockList[i].unlockEpoch > _currentEpoch) { lengthPendingUnlocks += 1; } } pendingUnlocks = new EpochUnlockInfo[](lengthPendingUnlocks); lengthPendingUnlocks = 0; for (uint256 i = _nextUnlockIndex; i < _pendingUnlockList.length; i++) { if (_pendingUnlockList[i].unlockEpoch > _currentEpoch) { pendingUnlocks[lengthPendingUnlocks] = _pendingUnlockList[i]; lengthPendingUnlocks += 1; } } } /// @dev Return the total amount of free CVX in this contract, including staked in CVXRewardPool. /// @return The amount of CVX in this contract now. function totalCVXInPool() public view returns (uint256) { return IERC20Upgradeable(CVX).balanceOf(address(this)).add( IConvexCVXRewardPool(CVX_REWARD_POOL).balanceOf(address(this)) ); } /********************************** Mutated Functions **********************************/ /// @dev Deposit CVX and lock into CVXLockerV2 /// @param _amount The amount of CVX to lock. function deposit(uint256 _amount) external override { require(_amount > 0, "CLeverCVXLocker: deposit zero CVX"); IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _amount); // 1. update reward info _updateReward(msg.sender); // 2. lock to CVXLockerV2 IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, 0); IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, _amount); IConvexCVXLocker(CVX_LOCKER).lock(address(this), _amount, 0); // 3. update user lock info uint256 _currentEpoch = block.timestamp / REWARDS_DURATION; uint256 _reminder = _currentEpoch % 17; UserInfo storage _info = userInfo[msg.sender]; _info.totalLocked = uint112(_amount + uint256(_info.totalLocked)); // should never overflow _info.epochLocked[_reminder] = _amount + _info.epochLocked[_reminder]; // should never overflow // 4. update global info totalLockedGlobal = _amount.add(totalLockedGlobal); // direct cast shoule be safe emit Deposit(msg.sender, _amount); } /// @dev Unlock CVX from the CVXLockerV2 /// Notice that all pending unlocked CVX will not share future rewards. /// @param _amount The amount of CVX to unlock. function unlock(uint256 _amount) external override { require(_amount > 0, "CLeverCVXLocker: unlock zero CVX"); // 1. update reward info _updateReward(msg.sender); // 2. update unlocked info _updateUnlocked(msg.sender); // 3. check unlock limit and update UserInfo storage _info = userInfo[msg.sender]; { uint256 _totalLocked = _info.totalLocked; uint256 _totalDebt = _info.totalDebt; require(_amount <= _totalLocked, "CLeverCVXLocker: insufficient CVX to unlock"); _checkAccountHealth(_totalLocked, _totalDebt, _amount, 0); // if you choose unlock, all pending unlocked CVX will not share the reward. _info.totalLocked = uint112(_totalLocked - _amount); // should never overflow // global unlock info will be updated in `processUnlockableCVX` totalLockedGlobal -= _amount; totalPendingUnlockGlobal += _amount; } emit Unlock(msg.sender, _amount); // 4. enumerate lockInfo array to unlock uint256 _nextEpoch = block.timestamp / REWARDS_DURATION + 1; EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList; uint256 _index; uint256 _locked; uint256 _unlocked; for (uint256 i = 0; i < 17; i++) { _index = _nextEpoch % 17; _locked = _info.epochLocked[_index]; if (_amount >= _locked) _unlocked = _locked; else _unlocked = _amount; if (_unlocked > 0) { _info.epochLocked[_index] = _locked - _unlocked; // should never overflow _amount = _amount - _unlocked; // should never overflow pendingUnlocked[_nextEpoch] = pendingUnlocked[_nextEpoch] + _unlocked; // should never overflow if ( _pendingUnlockList.length == 0 || _pendingUnlockList[_pendingUnlockList.length - 1].unlockEpoch != _nextEpoch ) { _pendingUnlockList.push( EpochUnlockInfo({ pendingUnlock: uint192(_unlocked), unlockEpoch: uint64(_nextEpoch) }) ); } else { _pendingUnlockList[_pendingUnlockList.length - 1].pendingUnlock = uint192( _unlocked + _pendingUnlockList[_pendingUnlockList.length - 1].pendingUnlock ); } } if (_amount == 0) break; _nextEpoch = _nextEpoch + 1; } } /// @dev Withdraw all unlocked CVX from this contract. function withdrawUnlocked() external override { // 1. update reward info _updateReward(msg.sender); // 2. update unlocked info _updateUnlocked(msg.sender); // 3. claim unlocked CVX UserInfo storage _info = userInfo[msg.sender]; uint256 _unlocked = _info.totalUnlocked; _info.totalUnlocked = 0; // update global info totalUnlockedGlobal = totalUnlockedGlobal.sub(_unlocked); uint256 _balanceInContract = IERC20Upgradeable(CVX).balanceOf(address(this)); // balance is not enough, with from reward pool if (_balanceInContract < _unlocked) { IConvexCVXRewardPool(CVX_REWARD_POOL).withdraw(_unlocked - _balanceInContract, false); } IERC20Upgradeable(CVX).safeTransfer(msg.sender, _unlocked); emit Withdraw(msg.sender, _unlocked); } /// @dev Repay clevCVX debt with CVX or clevCVX. /// @param _cvxAmount The amount of CVX used to pay debt. /// @param _clevCVXAmount The amount of clevCVX used to pay debt. function repay(uint256 _cvxAmount, uint256 _clevCVXAmount) external override { require(_cvxAmount > 0 || _clevCVXAmount > 0, "CLeverCVXLocker: repay zero amount"); // 1. update reward info _updateReward(msg.sender); UserInfo storage _info = userInfo[msg.sender]; uint256 _totalDebt = _info.totalDebt; uint256 _totalDebtGlobal = totalDebtGlobal; // 3. check repay with cvx and take fee if (_cvxAmount > 0 && _totalDebt > 0) { if (_cvxAmount > _totalDebt) _cvxAmount = _totalDebt; uint256 _fee = _cvxAmount.mul(repayFeePercentage) / FEE_DENOMINATOR; _totalDebt = _totalDebt - _cvxAmount; // never overflow _totalDebtGlobal = _totalDebtGlobal - _cvxAmount; // never overflow // distribute to furnace and transfer fee to platform IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _cvxAmount + _fee); if (_fee > 0) { IERC20Upgradeable(CVX).safeTransfer(platform, _fee); } address _furnace = furnace; IERC20Upgradeable(CVX).safeApprove(_furnace, 0); IERC20Upgradeable(CVX).safeApprove(_furnace, _cvxAmount); IFurnace(_furnace).distribute(address(this), _cvxAmount); } // 4. check repay with clevCVX if (_clevCVXAmount > 0 && _totalDebt > 0) { if (_clevCVXAmount > _totalDebt) _clevCVXAmount = _totalDebt; uint256 _fee = _clevCVXAmount.mul(repayFeePercentage) / FEE_DENOMINATOR; _totalDebt = _totalDebt - _clevCVXAmount; // never overflow _totalDebtGlobal = _totalDebtGlobal - _clevCVXAmount; // burn debt token and tranfer fee to platform if (_fee > 0) { IERC20Upgradeable(clevCVX).safeTransferFrom(msg.sender, platform, _fee); } ICLeverToken(clevCVX).burnFrom(msg.sender, _clevCVXAmount); } _info.totalDebt = uint128(_totalDebt); totalDebtGlobal = _totalDebtGlobal; emit Repay(msg.sender, _cvxAmount, _clevCVXAmount); } /// @dev Borrow clevCVX from this contract. /// Notice the reward will be used first and it will not be treated as debt. /// @param _amount The amount of clevCVX to borrow. /// @param _depositToFurnace Whether to deposit borrowed clevCVX to furnace. function borrow(uint256 _amount, bool _depositToFurnace) external override { require(_amount > 0, "CLeverCVXLocker: borrow zero amount"); // 1. update reward info _updateReward(msg.sender); UserInfo storage _info = userInfo[msg.sender]; uint256 _rewards = _info.rewards; uint256 _borrowWithLocked; // 2. borrow with rewards, this will not be treated as debt. if (_rewards >= _amount) { _info.rewards = uint128(_rewards - _amount); } else { _info.rewards = 0; _borrowWithLocked = _amount - _rewards; } // 3. borrow with locked CVX if (_borrowWithLocked > 0) { uint256 _totalLocked = _info.totalLocked; uint256 _totalDebt = _info.totalDebt; _checkAccountHealth(_totalLocked, _totalDebt, 0, _borrowWithLocked); // update user info _info.totalDebt = uint128(_totalDebt + _borrowWithLocked); // should not overflow. // update global info totalDebtGlobal = totalDebtGlobal + _borrowWithLocked; // should not overflow. } _mintOrDeposit(_amount, _depositToFurnace); emit Borrow(msg.sender, _amount); } /// @dev Someone donate CVX to all CVX locker in this contract. /// @param _amount The amount of CVX to donate. function donate(uint256 _amount) external override { require(_amount > 0, "CLeverCVXLocker: donate zero amount"); IERC20Upgradeable(CVX).safeTransferFrom(msg.sender, address(this), _amount); _distribute(_amount); } /// @dev Harvest pending reward from CVXLockerV2 and CVXRewardPool, then swap it to CVX. /// @param _recipient - The address of account to receive harvest bounty. /// @param _minimumOut - The minimum amount of CVX should get. /// @return The amount of CVX harvested. function harvest(address _recipient, uint256 _minimumOut) external override returns (uint256) { // 1. harvest from CVXLockerV2 and CVXRewardPool IConvexCVXRewardPool(CVX_REWARD_POOL).getReward(false); IConvexCVXLocker(CVX_LOCKER).getReward(address(this)); // 2. convert all CVXCRV to CVX uint256 _amount = IERC20Upgradeable(CVXCRV).balanceOf(address(this)); if (_amount > 0) { IERC20Upgradeable(CVXCRV).safeTransfer(zap, _amount); _amount = IZap(zap).zap(CVXCRV, _amount, CVX, _minimumOut); } require(_amount >= _minimumOut, "CLeverCVXLocker: insufficient output"); // 3. distribute incentive to platform and _recipient uint256 _platformFee = platformFeePercentage; uint256 _distributeAmount = _amount; if (_platformFee > 0) { _platformFee = (_distributeAmount * _platformFee) / FEE_DENOMINATOR; _distributeAmount = _distributeAmount - _platformFee; IERC20Upgradeable(CVX).safeTransfer(platform, _platformFee); } uint256 _harvestBounty = harvestBountyPercentage; if (_harvestBounty > 0) { _harvestBounty = (_distributeAmount * _harvestBounty) / FEE_DENOMINATOR; _distributeAmount = _distributeAmount - _harvestBounty; IERC20Upgradeable(CVX).safeTransfer(_recipient, _harvestBounty); } // 4. distribute to users _distribute(_distributeAmount); emit Harvest(msg.sender, _distributeAmount, _platformFee, _harvestBounty); return _amount; } /// @dev Harvest pending reward from Votium, then swap it to CVX. /// @param claims The parameters used by VotiumMultiMerkleStash contract. /// @param _minimumOut - The minimum amount of CVX should get. /// @return The amount of CVX harvested. function harvestVotium(IVotiumMultiMerkleStash.claimParam[] calldata claims, uint256 _minimumOut) external override onlyKeeper returns (uint256) { // 1. claim reward from votium for (uint256 i = 0; i < claims.length; i++) { // in case someone has claimed the reward for this contract, we can still call this function to process reward. if (!IVotiumMultiMerkleStash(VOTIUM_DISTRIBUTOR).isClaimed(claims[i].token, claims[i].index)) { IVotiumMultiMerkleStash(VOTIUM_DISTRIBUTOR).claim( claims[i].token, claims[i].index, address(this), claims[i].amount, claims[i].merkleProof ); } } address[] memory _rewardTokens = new address[](claims.length); uint256[] memory _amounts = new uint256[](claims.length); for (uint256 i = 0; i < claims.length; i++) { _rewardTokens[i] = claims[i].token; // TODO: consider fee on transfer token (currently, such token doesn't exsist) _amounts[i] = claims[i].amount; } // 2. swap all tokens to CVX uint256 _amount = _swapToCVX(_rewardTokens, _amounts, _minimumOut); // 3. distribute to platform uint256 _distributeAmount = _amount; uint256 _platformFee = platformFeePercentage; if (_platformFee > 0) { _platformFee = (_distributeAmount * _platformFee) / FEE_DENOMINATOR; _distributeAmount = _distributeAmount - _platformFee; IERC20Upgradeable(CVX).safeTransfer(platform, _platformFee); } // 4. distribute to users _distribute(_distributeAmount); emit Harvest(msg.sender, _distributeAmount, _platformFee, 0); return _amount; } /// @dev Process unlocked CVX in CVXLockerV2. /// /// This function should be called every week if /// 1. `pendingUnlocked[currentEpoch]` is nonzero. /// 2. some CVX is unlocked in current epoch. function processUnlockableCVX() external onlyKeeper { // Be careful that someone may kick us out from CVXLockerV2 // `totalUnlockedGlobal` keep track the amount of CVX unlocked from CVXLockerV2 // all other CVX in this contract can be considered unlocked from CVXLockerV2 by someone else. // 1. find extra CVX from donation or kicked out from CVXLockerV2 uint256 _extraCVX = totalCVXInPool().sub(totalUnlockedGlobal); // 2. unlock CVX uint256 _unlocked = IERC20Upgradeable(CVX).balanceOf(address(this)); IConvexCVXLocker(CVX_LOCKER).processExpiredLocks(false); _unlocked = IERC20Upgradeable(CVX).balanceOf(address(this)).sub(_unlocked).add(_extraCVX); // 3. remove user unlocked CVX uint256 currentEpoch = block.timestamp / REWARDS_DURATION; uint256 _pending = pendingUnlocked[currentEpoch]; if (_pending > 0) { // check if the unlocked CVX is enough, normally this should always be true. require(_unlocked >= _pending, "CLeverCVXLocker: insufficient unlocked CVX"); _unlocked -= _pending; // update global info totalUnlockedGlobal = totalUnlockedGlobal.add(_pending); totalPendingUnlockGlobal -= _pending; // should never overflow pendingUnlocked[currentEpoch] = 0; } // 4. relock if (_unlocked > 0) { IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, 0); IERC20Upgradeable(CVX).safeApprove(CVX_LOCKER, _unlocked); IConvexCVXLocker(CVX_LOCKER).lock(address(this), _unlocked, 0); } } /********************************** Restricted Functions **********************************/ /// @dev delegate vlCVX voting power. /// @param _registry The address of Snapshot Delegate Registry. /// @param _id The id for which the delegate should be set. /// @param _delegate The address of the delegate. function delegate( address _registry, bytes32 _id, address _delegate ) external onlyGovernorOrOwner { ISnapshotDelegateRegistry(_registry).setDelegate(_id, _delegate); } /// @dev Update the address of governor. /// @param _governor The address to be updated function updateGovernor(address _governor) external onlyGovernorOrOwner { require(_governor != address(0), "CLeverCVXLocker: zero governor address"); governor = _governor; emit UpdateGovernor(_governor); } /// @dev Update stake percentage for CVX in this contract. /// @param _percentage The stake percentage to be updated, multipled by 1e9. function updateStakePercentage(uint256 _percentage) external onlyGovernorOrOwner { require(_percentage <= FEE_DENOMINATOR, "CLeverCVXLocker: percentage too large"); stakePercentage = _percentage; emit UpdateStakePercentage(_percentage); } /// @dev Update stake threshold for CVX. /// @param _threshold The stake threshold to be updated. function updateStakeThreshold(uint256 _threshold) external onlyGovernorOrOwner { stakeThreshold = _threshold; emit UpdateStakeThreshold(_threshold); } /// @dev Update manual swap reward token lists. /// @param _tokens The addresses of token list. /// @param _status The status to be updated. function updateManualSwapRewardToken(address[] memory _tokens, bool _status) external onlyGovernorOrOwner { for (uint256 i = 0; i < _tokens.length; i++) { require(_tokens[i] != CVX, "CLeverCVXLocker: invalid token"); manualSwapRewardToken[_tokens[i]] = _status; } } /// @dev Update the repay fee percentage. /// @param _feePercentage - The fee percentage to update. function updateRepayFeePercentage(uint256 _feePercentage) external onlyOwner { require(_feePercentage <= MAX_REPAY_FEE, "AladdinCRV: fee too large"); repayFeePercentage = _feePercentage; emit UpdateRepayFeePercentage(_feePercentage); } /// @dev Update the platform fee percentage. /// @param _feePercentage - The fee percentage to update. function updatePlatformFeePercentage(uint256 _feePercentage) external onlyOwner { require(_feePercentage <= MAX_PLATFORM_FEE, "AladdinCRV: fee too large"); platformFeePercentage = _feePercentage; emit UpdatePlatformFeePercentage(_feePercentage); } /// @dev Update the harvest bounty percentage. /// @param _percentage - The fee percentage to update. function updateHarvestBountyPercentage(uint256 _percentage) external onlyOwner { require(_percentage <= MAX_HARVEST_BOUNTY, "AladdinCRV: fee too large"); harvestBountyPercentage = _percentage; emit UpdateHarvestBountyPercentage(_percentage); } /// @dev Update the recipient function updatePlatform(address _platform) external onlyOwner { require(_platform != address(0), "AladdinCRV: zero platform address"); platform = _platform; emit UpdatePlatform(_platform); } /// @dev Update the zap contract function updateZap(address _zap) external onlyGovernorOrOwner { require(_zap != address(0), "CLeverCVXLocker: zero zap address"); zap = _zap; emit UpdateZap(_zap); } function updateReserveRate(uint256 _reserveRate) external onlyOwner { require(_reserveRate <= FEE_DENOMINATOR, "CLeverCVXLocker: invalid reserve rate"); reserveRate = _reserveRate; } /// @dev Withdraw all manual swap reward tokens from the contract. /// @param _tokens The address list of tokens to withdraw. /// @param _recipient The address of user who will recieve the tokens. function withdrawManualSwapRewardTokens(address[] memory _tokens, address _recipient) external onlyOwner { for (uint256 i = 0; i < _tokens.length; i++) { if (!manualSwapRewardToken[_tokens[i]]) continue; uint256 _balance = IERC20Upgradeable(_tokens[i]).balanceOf(address(this)); IERC20Upgradeable(_tokens[i]).safeTransfer(_recipient, _balance); } } /// @dev Update keepers. /// @param _accounts The address list of keepers to update. /// @param _status The status of updated keepers. function updateKeepers(address[] memory _accounts, bool _status) external onlyGovernorOrOwner { for (uint256 i = 0; i < _accounts.length; i++) { isKeeper[_accounts[i]] = _status; } } /********************************** Internal Functions **********************************/ /// @dev Internal function called by `deposit`, `unlock`, `withdrawUnlocked`, `repay`, `borrow` and `claim`. /// @param _account The address of account to update reward info. function _updateReward(address _account) internal { UserInfo storage _info = userInfo[_account]; require(_info.lastInteractedBlock != block.number, "CLeverCVXLocker: enter the same block"); uint256 _totalDebtGlobal = totalDebtGlobal; uint256 _totalDebt = _info.totalDebt; uint256 _rewards = uint256(_info.rewards).add( accRewardPerShare.sub(_info.rewardPerSharePaid).mul(_info.totalLocked) / PRECISION ); _info.rewardPerSharePaid = uint192(accRewardPerShare); // direct cast should be safe _info.lastInteractedBlock = uint64(block.number); // pay debt with reward if possible if (_totalDebt > 0) { if (_rewards >= _totalDebt) { _rewards -= _totalDebt; _totalDebtGlobal -= _totalDebt; _totalDebt = 0; } else { _totalDebtGlobal -= _rewards; _totalDebt -= _rewards; _rewards = 0; } } _info.totalDebt = uint128(_totalDebt); // direct cast should be safe _info.rewards = uint128(_rewards); // direct cast should be safe totalDebtGlobal = _totalDebtGlobal; } /// @dev Internal function called by `unlock`, `withdrawUnlocked`. /// @param _account The address of account to update pending unlock list. function _updateUnlocked(address _account) internal { UserInfo storage _info = userInfo[_account]; uint256 _currentEpoch = block.timestamp / REWARDS_DURATION; uint256 _nextUnlockIndex = _info.nextUnlockIndex; uint256 _totalUnlocked = _info.totalUnlocked; EpochUnlockInfo[] storage _pendingUnlockList = _info.pendingUnlockList; uint256 _unlockEpoch; uint256 _unlockAmount; while (_nextUnlockIndex < _pendingUnlockList.length) { _unlockEpoch = _pendingUnlockList[_nextUnlockIndex].unlockEpoch; _unlockAmount = _pendingUnlockList[_nextUnlockIndex].pendingUnlock; if (_unlockEpoch <= _currentEpoch) { _totalUnlocked = _totalUnlocked + _unlockAmount; delete _pendingUnlockList[_nextUnlockIndex]; // clear entry to refund gas } else { break; } _nextUnlockIndex += 1; } _info.totalUnlocked = uint112(_totalUnlocked); _info.nextUnlockIndex = uint32(_nextUnlockIndex); } /// @dev Internal function used to swap tokens to CVX. /// @param _rewardTokens The address list of reward tokens. /// @param _amounts The amount list of reward tokens. /// @param _minimumOut The minimum amount of CVX should get. /// @return The amount of CVX swapped. function _swapToCVX( address[] memory _rewardTokens, uint256[] memory _amounts, uint256 _minimumOut ) internal returns (uint256) { uint256 _amount; address _token; address _zap = zap; for (uint256 i = 0; i < _rewardTokens.length; i++) { _token = _rewardTokens[i]; // skip manual swap token if (manualSwapRewardToken[_token]) continue; if (_token != CVX) { if (_amounts[i] > 0) { IERC20Upgradeable(_token).safeTransfer(_zap, _amounts[i]); _amount = _amount.add(IZap(_zap).zap(_token, _amounts[i], CVX, 0)); } } else { _amount = _amount.add(_amounts[i]); } } require(_amount >= _minimumOut, "CLeverCVXLocker: insufficient output"); return _amount; } /// @dev Internal function called by `harvest` and `harvestVotium`. function _distribute(uint256 _amount) internal { // 1. update reward info uint256 _totalLockedGlobal = totalLockedGlobal; // gas saving // It's ok to donate when on one is locking in this contract. if (_totalLockedGlobal > 0) { accRewardPerShare = accRewardPerShare.add(_amount.mul(PRECISION) / uint256(_totalLockedGlobal)); } // 2. distribute reward CVX to Furnace address _furnace = furnace; IERC20Upgradeable(CVX).safeApprove(_furnace, 0); IERC20Upgradeable(CVX).safeApprove(_furnace, _amount); IFurnace(_furnace).distribute(address(this), _amount); // 3. stake extra CVX to cvxRewardPool uint256 _balanceStaked = IConvexCVXRewardPool(CVX_REWARD_POOL).balanceOf(address(this)); uint256 _toStake = _balanceStaked.add(IERC20Upgradeable(CVX).balanceOf(address(this))).mul(stakePercentage).div( FEE_DENOMINATOR ); if (_balanceStaked < _toStake) { _toStake = _toStake - _balanceStaked; if (_toStake >= stakeThreshold) { IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, 0); IERC20Upgradeable(CVX).safeApprove(CVX_REWARD_POOL, _toStake); IConvexCVXRewardPool(CVX_REWARD_POOL).stake(_toStake); } } } /// @dev Internal function used to help to mint clevCVX. /// @param _amount The amount of clevCVX to mint. /// @param _depositToFurnace Whether to deposit the minted clevCVX to furnace. function _mintOrDeposit(uint256 _amount, bool _depositToFurnace) internal { if (_depositToFurnace) { address _clevCVX = clevCVX; address _furnace = furnace; // stake clevCVX to furnace. ICLeverToken(_clevCVX).mint(address(this), _amount); IERC20Upgradeable(_clevCVX).safeApprove(_furnace, 0); IERC20Upgradeable(_clevCVX).safeApprove(_furnace, _amount); IFurnace(_furnace).depositFor(msg.sender, _amount); } else { // transfer clevCVX to sender. ICLeverToken(clevCVX).mint(msg.sender, _amount); } } /// @dev Internal function to check the health of account. /// And account is health if and only if /// cvxBorrowed /// cvxDeposited >= -------------- /// cvxReserveRate /// @param _totalDeposited The amount of CVX currently deposited. /// @param _totalDebt The amount of clevCVX currently borrowed. /// @param _newUnlock The amount of CVX to unlock. /// @param _newBorrow The amount of clevCVX to borrow. function _checkAccountHealth( uint256 _totalDeposited, uint256 _totalDebt, uint256 _newUnlock, uint256 _newBorrow ) internal view { require( _totalDeposited.sub(_newUnlock).mul(reserveRate) >= _totalDebt.add(_newBorrow).mul(FEE_DENOMINATOR), "CLeverCVXLocker: unlock or borrow exceeds limit" ); } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.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 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"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./IVotiumMultiMerkleStash.sol"; interface ICLeverCVXLocker { event Deposit(address indexed _account, uint256 _amount); event Unlock(address indexed _account, uint256 _amount); event Withdraw(address indexed _account, uint256 _amount); event Repay(address indexed _account, uint256 _cvxAmount, uint256 _clevCVXAmount); event Borrow(address indexed _account, uint256 _amount); event Claim(address indexed _account, uint256 _amount); event Harvest(address indexed _caller, uint256 _reward, uint256 _platformFee, uint256 _harvestBounty); function getUserInfo(address _account) external view returns ( uint256 totalDeposited, uint256 totalPendingUnlocked, uint256 totalUnlocked, uint256 totalBorrowed, uint256 totalReward ); function deposit(uint256 _amount) external; function unlock(uint256 _amount) external; function withdrawUnlocked() external; function repay(uint256 _cvxAmount, uint256 _clevCVXAmount) external; function borrow(uint256 _amount, bool _depositToFurnace) external; function donate(uint256 _amount) external; function harvest(address _recipient, uint256 _minimumOut) external returns (uint256); function harvestVotium(IVotiumMultiMerkleStash.claimParam[] calldata claims, uint256 _minimumOut) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ICLeverToken is IERC20 { function mint(address _recipient, uint256 _amount) external; function burn(uint256 _amount) external; function burnFrom(address _account, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface IConvexCVXLocker { struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } function lockedBalanceOf(address _user) external view returns (uint256 amount); // Information on a user's locked balances function lockedBalances(address _user) external view returns ( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; function processExpiredLocks(bool _relock) external; function kickExpiredLocks(address _account) external; function getReward(address _account, bool _stake) external; function getReward(address _account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IConvexCVXRewardPool { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function withdraw(uint256 _amount, bool claim) external; function withdrawAll(bool claim) external; function stake(uint256 _amount) external; function stakeAll() external; function stakeFor(address _for, uint256 _amount) external; function getReward( address _account, bool _claimExtras, bool _stake ) external; function getReward(bool _stake) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IFurnace { event Deposit(address indexed _account, uint256 _amount); event Withdraw(address indexed _account, address _recipient, uint256 _amount); event Claim(address indexed _account, address _recipient, uint256 _amount); event Distribute(address indexed _origin, uint256 _amount); event Harvest(address indexed _caller, uint256 _amount); /// @dev Return the amount of clevCVX unrealised and realised of user. /// @param _account The address of user. /// @return unrealised The amount of clevCVX unrealised. /// @return realised The amount of clevCVX realised and can be claimed. function getUserInfo(address _account) external view returns (uint256 unrealised, uint256 realised); /// @dev Deposit clevCVX in this contract to change for CVX. /// @param _amount The amount of clevCVX to deposit. function deposit(uint256 _amount) external; /// @dev Deposit clevCVX in this contract to change for CVX for other user. /// @param _account The address of user you deposit for. /// @param _amount The amount of clevCVX to deposit. function depositFor(address _account, uint256 _amount) external; /// @dev Withdraw unrealised clevCVX of the caller from this contract. /// @param _recipient The address of user who will recieve the clevCVX. /// @param _amount The amount of clevCVX to withdraw. function withdraw(address _recipient, uint256 _amount) external; /// @dev Withdraw all unrealised clevCVX of the caller from this contract. /// @param _recipient The address of user who will recieve the clevCVX. function withdrawAll(address _recipient) external; /// @dev Claim all realised CVX of the caller from this contract. /// @param _recipient The address of user who will recieve the CVX. function claim(address _recipient) external; /// @dev Exit the contract, withdraw all unrealised clevCVX and realised CVX of the caller. /// @param _recipient The address of user who will recieve the clevCVX and CVX. function exit(address _recipient) external; /// @dev Distribute CVX from `origin` to pay clevCVX debt. /// @param _origin The address of the user who will provide CVX. /// @param _amount The amount of CVX will be provided. function distribute(address _origin, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface ISnapshotDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IZap { function zap( address _fromToken, uint256 _amountIn, address _toToken, uint256 _minOut ) external payable returns (uint256); } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface IVotiumMultiMerkleStash { // solhint-disable-next-line contract-name-camelcase struct claimParam { address token; uint256 index; uint256 amount; bytes32[] merkleProof; } function isClaimed(address token, uint256 index) external view returns (bool); function claim( address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; function claimMulti(address account, claimParam[] calldata claims) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
@dev Update keepers. @param _accounts The address list of keepers to update. @param _status The status of updated keepers.
function updateKeepers(address[] memory _accounts, bool _status) external onlyGovernorOrOwner { for (uint256 i = 0; i < _accounts.length; i++) { isKeeper[_accounts[i]] = _status; } }
14,939,472
[ 1, 1891, 3455, 414, 18, 225, 389, 13739, 1021, 1758, 666, 434, 3455, 414, 358, 1089, 18, 225, 389, 2327, 1021, 1267, 434, 3526, 3455, 414, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 11523, 414, 12, 2867, 8526, 3778, 389, 13739, 16, 1426, 389, 2327, 13, 3903, 1338, 43, 1643, 29561, 1162, 5541, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 13739, 18, 2469, 31, 277, 27245, 288, 203, 1377, 353, 17891, 63, 67, 13739, 63, 77, 13563, 273, 389, 2327, 31, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; pragma experimental ABIEncoderV2; /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Modifiable * @notice A contract with basic modifiers */ contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SelfDestructible * @notice Contract that allows for self-destruction */ contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Ownable * @notice A modifiable that has ownership roles */ contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Servable * @notice An ownable that contains registered services and their actions */ contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string action) { require(isEnabledServiceAction(msg.sender, action)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathIntLib * @dev Math operations with safety checks that throw on error */ library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbUintsLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; uint256 value; } struct BlockNumbUints { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbUints storage self) internal view returns (uint256) { return valueAt(self, block.number); } function currentEntry(BlockNumbUints storage self) internal view returns (Entry) { return entryAt(self, block.number); } function valueAt(BlockNumbUints storage self, uint256 _blockNumber) internal view returns (uint256) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbUints storage self, uint256 _blockNumber) internal view returns (Entry) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbUints storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbUints storage self) internal view returns (Entry[]) { return self.entries; } function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbIntsLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; int256 value; } struct BlockNumbInts { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbInts storage self) internal view returns (int256) { return valueAt(self, block.number); } function currentEntry(BlockNumbInts storage self) internal view returns (Entry) { return entryAt(self, block.number); } function valueAt(BlockNumbInts storage self, uint256 _blockNumber) internal view returns (int256) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbInts storage self, uint256 _blockNumber) internal view returns (Entry) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbInts storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbInts storage self) internal view returns (Entry[]) { return self.entries; } function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbDisdIntsLib { using SafeMathIntLib for int256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Discount { int256 tier; int256 value; } struct Entry { uint256 blockNumber; int256 nominal; Discount[] discounts; } struct BlockNumbDisdInts { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentNominalValue(BlockNumbDisdInts storage self) internal view returns (int256) { return nominalValueAt(self, block.number); } function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier) internal view returns (int256) { return discountedValueAt(self, block.number, tier); } function currentEntry(BlockNumbDisdInts storage self) internal view returns (Entry) { return entryAt(self, block.number); } function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber) internal view returns (int256) { return entryAt(self, _blockNumber).nominal; } function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier) internal view returns (int256) { Entry memory entry = entryAt(self, _blockNumber); if (0 < entry.discounts.length) { uint256 index = indexByTier(entry.discounts, tier); if (0 < index) return entry.nominal.mul( ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value) ).div( ConstantsLib.PARTS_PER() ); else return entry.nominal; } else return entry.nominal; } function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber) internal view returns (Entry) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.length++; Entry storage entry = self.entries[self.entries.length - 1]; entry.blockNumber = blockNumber; entry.nominal = nominal; } function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) internal { require(discountTiers.length == discountValues.length); addNominalEntry(self, blockNumber, nominal); Entry storage entry = self.entries[self.entries.length - 1]; for (uint256 i = 0; i < discountTiers.length; i++) entry.discounts.push(Discount(discountTiers[i], discountValues[i])); } function count(BlockNumbDisdInts storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbDisdInts storage self) internal view returns (Entry[]) { return self.entries; } function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } /// @dev The index returned here is 1-based function indexByTier(Discount[] discounts, int256 tier) internal pure returns (uint256) { require(0 < discounts.length); for (uint256 i = discounts.length; i > 0; i--) if (tier >= discounts[i - 1].tier) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title MonetaryTypesLib * @dev Monetary data types */ library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbReferenceCurrenciesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; MonetaryTypesLib.Currency currency; } struct BlockNumbReferenceCurrencies { mapping(address => mapping(uint256 => Entry[])) entriesByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (MonetaryTypesLib.Currency storage) { return currencyAt(self, referenceCurrency, block.number); } function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (Entry storage) { return entryAt(self, referenceCurrency, block.number); } function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 _blockNumber) internal view returns (MonetaryTypesLib.Currency storage) { return entryAt(self, referenceCurrency, _blockNumber).currency; } function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 _blockNumber) internal view returns (Entry storage) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)]; } function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber, MonetaryTypesLib.Currency referenceCurrency, MonetaryTypesLib.Currency currency) internal { require( 0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length || blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber ); self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency)); } function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (uint256) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length; } function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (Entry[] storage) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id]; } function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length); for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--) if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbFiguresLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; MonetaryTypesLib.Figure value; } struct BlockNumbFigures { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbFigures storage self) internal view returns (MonetaryTypesLib.Figure storage) { return valueAt(self, block.number); } function currentEntry(BlockNumbFigures storage self) internal view returns (Entry storage) { return entryAt(self, block.number); } function valueAt(BlockNumbFigures storage self, uint256 _blockNumber) internal view returns (MonetaryTypesLib.Figure storage) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbFigures storage self, uint256 _blockNumber) internal view returns (Entry storage) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbFigures storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbFigures storage self) internal view returns (Entry[] storage) { return self.entries; } function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Configuration * @notice An oracle for configurations values */ contract Configuration is Modifiable, Ownable, Servable { using SafeMathIntLib for int256; using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints; using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts; using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts; using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies; using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public OPERATIONAL_MODE_ACTION = "operational_mode"; // // Enums // ----------------------------------------------------------------------------------------------------------------- enum OperationalMode {Normal, Exit} // // Variables // ----------------------------------------------------------------------------------------------------------------- OperationalMode public operationalMode = OperationalMode.Normal; BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber; BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber; mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber; mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber; BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber; BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber; BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber; BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber; BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber; uint256 public earliestSettlementBlockNumber; bool public earliestSettlementBlockNumberUpdateDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetOperationalModeExitEvent(); event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks); event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks); event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal); event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId, address feeCurrencyCt, uint256 feeCurrencyId); event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt, uint256 stakeCurrencyId); event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber); event DisableEarliestSettlementBlockNumberUpdateEvent(); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { updateDelayBlocksByBlockNumber.addEntry(block.number, 0); } // // Public functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set operational mode to Exit /// @dev Once operational mode is set to Exit it may not be set back to Normal function setOperationalModeExit() public onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION) { operationalMode = OperationalMode.Exit; emit SetOperationalModeExitEvent(); } /// @notice Return true if operational mode is Normal function isOperationalModeNormal() public view returns (bool) { return OperationalMode.Normal == operationalMode; } /// @notice Return true if operational mode is Exit function isOperationalModeExit() public view returns (bool) { return OperationalMode.Exit == operationalMode; } /// @notice Get the current value of update delay blocks /// @return The value of update delay blocks function updateDelayBlocks() public view returns (uint256) { return updateDelayBlocksByBlockNumber.currentValue(); } /// @notice Get the count of update delay blocks values /// @return The count of update delay blocks values function updateDelayBlocksCount() public view returns (uint256) { return updateDelayBlocksByBlockNumber.count(); } /// @notice Set the number of update delay blocks /// @param fromBlockNumber Block number from which the update applies /// @param newUpdateDelayBlocks The new update delay blocks value function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks); emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks); } /// @notice Get the current value of confirmation blocks /// @return The value of confirmation blocks function confirmationBlocks() public view returns (uint256) { return confirmationBlocksByBlockNumber.currentValue(); } /// @notice Get the count of confirmation blocks values /// @return The count of confirmation blocks values function confirmationBlocksCount() public view returns (uint256) { return confirmationBlocksByBlockNumber.count(); } /// @notice Set the number of confirmation blocks /// @param fromBlockNumber Block number from which the update applies /// @param newConfirmationBlocks The new confirmation blocks value function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks); emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks); } /// @notice Get number of trade maker fee block number tiers function tradeMakerFeesCount() public view returns (uint256) { return tradeMakerFeeByBlockNumber.count(); } /// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function tradeMakerFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of trade taker fee block number tiers function tradeTakerFeesCount() public view returns (uint256) { return tradeTakerFeeByBlockNumber.count(); } /// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function tradeTakerFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of payment fee block number tiers function paymentFeesCount() public view returns (uint256) { return paymentFeeByBlockNumber.count(); } /// @notice Get payment relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function paymentFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set payment nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of payment fee block number tiers of given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentFeesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count(); } /// @notice Get payment relative fee for given currency at given block number, possibly discounted by /// discount tier value /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param discountTier The concerned discount tier function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier) public view returns (int256) { if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count()) return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt( blockNumber, discountTier ); else return paymentFee(blockNumber, discountTier); } /// @notice Set payment nominal relative fee and discount tiers and values for given currency at given /// block number tier /// @param fromBlockNumber Block number from which the update applies /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry( fromBlockNumber, nominal, discountTiers, discountValues ); emit SetCurrencyPaymentFeeEvent( fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues ); } /// @notice Get number of minimum trade maker fee block number tiers function tradeMakerMinimumFeesCount() public view returns (uint256) { return tradeMakerMinimumFeeByBlockNumber.count(); } /// @notice Get trade maker minimum relative fee at given block number /// @param blockNumber The concerned block number function tradeMakerMinimumFee(uint256 blockNumber) public view returns (int256) { return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set trade maker minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum trade taker fee block number tiers function tradeTakerMinimumFeesCount() public view returns (uint256) { return tradeTakerMinimumFeeByBlockNumber.count(); } /// @notice Get trade taker minimum relative fee at given block number /// @param blockNumber The concerned block number function tradeTakerMinimumFee(uint256 blockNumber) public view returns (int256) { return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set trade taker minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum payment fee block number tiers function paymentMinimumFeesCount() public view returns (uint256) { return paymentMinimumFeeByBlockNumber.count(); } /// @notice Get payment minimum relative fee at given block number /// @param blockNumber The concerned block number function paymentMinimumFee(uint256 blockNumber) public view returns (int256) { return paymentMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set payment minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum payment fee block number tiers for given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count(); } /// @notice Get payment minimum relative fee for given currency at given block number /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId) public view returns (int256) { if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count()) return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber); else return paymentMinimumFee(blockNumber); } /// @notice Set payment minimum relative fee for given currency at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param nominal Minimum relative fee function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal); emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal); } /// @notice Get number of fee currencies for the given reference currency /// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20) function feeCurrenciesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId)); } /// @notice Get the fee currency for the given reference currency at given block number /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20) function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId) public view returns (address ct, uint256 id) { MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt( MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber ); ct = _feeCurrency.ct; id = _feeCurrency.id; } /// @notice Set the fee currency for the given reference currency at given block number /// @param fromBlockNumber Block number from which the update applies /// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20) /// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH) /// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20) function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId, address feeCurrencyCt, uint256 feeCurrencyId) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { feeCurrencyByCurrencyBlockNumber.addEntry( fromBlockNumber, MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId), MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId) ); emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId, feeCurrencyCt, feeCurrencyId); } /// @notice Get the current value of wallet lock timeout /// @return The value of wallet lock timeout function walletLockTimeout() public view returns (uint256) { return walletLockTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of wallet lock /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of cancel order challenge timeout /// @return The value of cancel order challenge timeout function cancelOrderChallengeTimeout() public view returns (uint256) { return cancelOrderChallengeTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of cancel order challenge /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of settlement challenge timeout /// @return The value of settlement challenge timeout function settlementChallengeTimeout() public view returns (uint256) { return settlementChallengeTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of settlement challenges /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of fraud stake fraction /// @return The value of fraud stake fraction function fraudStakeFraction() public view returns (uint256) { return fraudStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in fraud challenge /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of wallet settlement stake fraction /// @return The value of wallet settlement stake fraction function walletSettlementStakeFraction() public view returns (uint256) { return walletSettlementStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in settlement challenge triggered by wallet /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of operator settlement stake fraction /// @return The value of operator settlement stake fraction function operatorSettlementStakeFraction() public view returns (uint256) { return operatorSettlementStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in settlement challenge triggered by operator /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of operator settlement stake /// @return The value of operator settlement stake function operatorSettlementStake() public view returns (int256 amount, address currencyCt, uint256 currencyId) { MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue(); amount = stake.amount; currencyCt = stake.currency.ct; currencyId = stake.currency.id; } /// @notice Set figure of security bond that will be gained from successfully challenging /// in settlement challenge triggered by operator /// @param fromBlockNumber Block number from which the update applies /// @param stakeAmount The amount gained /// @param stakeCurrencyCt The address of currency gained /// @param stakeCurrencyId The ID of currency gained function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt, uint256 stakeCurrencyId) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId)); operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake); emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId); } /// @notice Set the block number of the earliest settlement initiation /// @param _earliestSettlementBlockNumber The block number of the earliest settlement function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber) public onlyOperator { earliestSettlementBlockNumber = _earliestSettlementBlockNumber; emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber); } /// @notice Disable further updates to the earliest settlement block number /// @dev This operation can not be undone function disableEarliestSettlementBlockNumberUpdate() public onlyOperator { earliestSettlementBlockNumberUpdateDisabled = true; emit DisableEarliestSettlementBlockNumberUpdateEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDelayedBlockNumber(uint256 blockNumber) { require( 0 == updateDelayBlocksByBlockNumber.count() || blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue() ); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Benefactor * @notice An ownable that has a client fund property */ contract Configurable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- Configuration public configuration; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the configuration contract /// @param newConfiguration The (address of) Configuration contract instance function setConfiguration(Configuration newConfiguration) public onlyDeployer notNullAddress(newConfiguration) notSameAddresses(newConfiguration, configuration) { // Set new configuration Configuration oldConfiguration = configuration; configuration = newConfiguration; // Emit event emit SetConfigurationEvent(oldConfiguration, newConfiguration); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier configurationInitialized() { require(configuration != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathUintLib * @dev Math operations with safety checks that throw on error */ library SafeMathUintLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency) { require(index < self.currencies.length); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[]) { require(0 < self.currencies.length); require(low <= up); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library NonFungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256[] ids; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256[])) idsByCurrency; mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[]) { return self.idsByCurrency[currencyCt][currencyId]; } function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) internal view returns (int256[]) { if (0 == self.idsByCurrency[currencyCt][currencyId].length) return new int256[](0); indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1); int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1); for (uint256 i = indexLow; i < indexUp; i++) idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i]; return idsByCurrency; } function idsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.idsByCurrency[currencyCt][currencyId].length; } function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 < self.idIndexById[currencyCt][currencyId][id]; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256[], uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256[], uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.ids, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[], uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.ids, record.blockNumber); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal { int256[] memory ids = new int256[](1); ids[0] = id; set(self, ids, currencyCt, currencyId); } function set(Balance storage self, int256[] ids, address currencyCt, uint256 currencyId) internal { uint256 i; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId] = ids; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function reset(Balance storage self, address currencyCt, uint256 currencyId) internal { for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId].length = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { if (0 < self.idIndexById[currencyCt][currencyId][id]) return false; self.idsByCurrency[currencyCt][currencyId].push(id); self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { uint256 index = self.idIndexById[currencyCt][currencyId][id]; if (0 == index) return false; if (index < self.idsByCurrency[currencyCt][currencyId].length) { self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1]; self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index; } self.idsByCurrency[currencyCt][currencyId].length--; self.idIndexById[currencyCt][currencyId][id] = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function transfer(Balance storage _from, Balance storage _to, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Balance tracker * @notice An ownable to track balances of generic types */ contract BalanceTracker is Ownable, Servable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using FungibleBalanceLib for FungibleBalanceLib.Balance; using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public DEPOSITED_BALANCE_TYPE = "deposited"; string constant public SETTLED_BALANCE_TYPE = "settled"; string constant public STAGED_BALANCE_TYPE = "staged"; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Wallet { mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType; mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType; } // // Variables // ----------------------------------------------------------------------------------------------------------------- bytes32 public depositedBalanceType; bytes32 public settledBalanceType; bytes32 public stagedBalanceType; bytes32[] public _allBalanceTypes; bytes32[] public _activeBalanceTypes; bytes32[] public trackedBalanceTypes; mapping(bytes32 => bool) public trackedBalanceTypeMap; mapping(address => Wallet) private walletMap; address[] public trackedWallets; mapping(address => uint256) public trackedWalletIndexByWallet; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE)); settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE)); stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE)); _allBalanceTypes.push(settledBalanceType); _allBalanceTypes.push(depositedBalanceType); _allBalanceTypes.push(stagedBalanceType); _activeBalanceTypes.push(settledBalanceType); _activeBalanceTypes.push(depositedBalanceType); } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the fungible balance (amount) of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The stored balance function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256) { return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId); } /// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param indexLow The lower index of IDs /// @param indexUp The upper index of IDs /// @return The stored balance function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) public view returns (int256[]) { return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices( currencyCt, currencyId, indexLow, indexUp ); } /// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The stored balance function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[]) { return walletMap[wallet].nonFungibleBalanceByType[_type].get( currencyCt, currencyId ); } /// @notice Get the count of non-fungible IDs of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of IDs function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount( currencyCt, currencyId ); } /// @notice Gauge whether the ID is included in the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param id The ID of the concerned unit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if ID is included, else false function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].nonFungibleBalanceByType[_type].hasId( id, currencyCt, currencyId ); } /// @notice Set the balance of the given wallet, type and currency to the given value /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to set /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if setting fungible balance, else false function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].set( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].set( value, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param ids The ids of non-fungible) to set /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function setIds(address wallet, bytes32 _type, int256[] ids, address currencyCt, uint256 currencyId) public onlyActiveService { // Update the balance walletMap[wallet].nonFungibleBalanceByType[_type].set( ids, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Add the given value to the balance of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to add /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if adding fungible balance, else false function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].add( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].add( value, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Subtract the given value from the balance of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to subtract /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if subtracting fungible balance, else false function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if data is stored, else false function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId); } /// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if data is stored, else false function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId); } /// @notice Get the count of fungible balance records for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of balance log entries function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } /// @notice Get the fungible balance record for the given wallet, type, currency /// log entry index /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param index The concerned record index /// @return The balance record function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// block number /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param _blockNumber The concerned block number /// @return The balance record function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } /// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The last log entry function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } /// @notice Get the count of non-fungible balance records for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of balance log entries function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// and record index /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param index The concerned record index /// @return The balance record function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// and block number /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param _blockNumber The concerned block number /// @return The balance record function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } /// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The last log entry function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } /// @notice Get the count of tracked balance types /// @return The count of tracked balance types function trackedBalanceTypesCount() public view returns (uint256) { return trackedBalanceTypes.length; } /// @notice Get the count of tracked wallets /// @return The count of tracked wallets function trackedWalletsCount() public view returns (uint256) { return trackedWallets.length; } /// @notice Get the default full set of balance types /// @return The set of all balance types function allBalanceTypes() public view returns (bytes32[]) { return _allBalanceTypes; } /// @notice Get the default set of active balance types /// @return The set of active balance types function activeBalanceTypes() public view returns (bytes32[]) { return _activeBalanceTypes; } /// @notice Get the subset of tracked wallets in the given index range /// @param low The lower index /// @param up The upper index /// @return The subset of tracked wallets function trackedWalletsByIndices(uint256 low, uint256 up) public view returns (address[]) { require(0 < trackedWallets.length); require(low <= up); up = up.clampMax(trackedWallets.length - 1); address[] memory _trackedWallets = new address[](up - low + 1); for (uint256 i = low; i <= up; i++) _trackedWallets[i - low] = trackedWallets[i]; return _trackedWallets; } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _updateTrackedBalanceTypes(bytes32 _type) private { if (!trackedBalanceTypeMap[_type]) { trackedBalanceTypeMap[_type] = true; trackedBalanceTypes.push(_type); } } function _updateTrackedWallets(address wallet) private { if (0 == trackedWalletIndexByWallet[wallet]) { trackedWallets.push(wallet); trackedWalletIndexByWallet[wallet] = trackedWallets.length; } } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title BalanceTrackable * @notice An ownable that has a balance tracker property */ contract BalanceTrackable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- BalanceTracker public balanceTracker; bool public balanceTrackerFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker); event FreezeBalanceTrackerEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the balance tracker contract /// @param newBalanceTracker The (address of) BalanceTracker contract instance function setBalanceTracker(BalanceTracker newBalanceTracker) public onlyDeployer notNullAddress(newBalanceTracker) notSameAddresses(newBalanceTracker, balanceTracker) { // Require that this contract has not been frozen require(!balanceTrackerFrozen); // Update fields BalanceTracker oldBalanceTracker = balanceTracker; balanceTracker = newBalanceTracker; // Emit event emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker); } /// @notice Freeze the balance tracker from further updates /// @dev This operation can not be undone function freezeBalanceTracker() public onlyDeployer { balanceTrackerFrozen = true; // Emit event emit FreezeBalanceTrackerEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier balanceTrackerInitialized() { require(balanceTracker != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NahmiiTypesLib * @dev Data types of general nahmii character */ library NahmiiTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum ChallengePhase {Dispute, Closed} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct OriginFigure { uint256 originId; MonetaryTypesLib.Figure figure; } struct IntendedConjugateCurrency { MonetaryTypesLib.Currency intended; MonetaryTypesLib.Currency conjugate; } struct SingleFigureTotalOriginFigures { MonetaryTypesLib.Figure single; OriginFigure[] total; } struct TotalOriginFigures { OriginFigure[] total; } struct CurrentPreviousInt256 { int256 current; int256 previous; } struct SingleTotalInt256 { int256 single; int256 total; } struct IntendedConjugateCurrentPreviousInt256 { CurrentPreviousInt256 intended; CurrentPreviousInt256 conjugate; } struct IntendedConjugateSingleTotalInt256 { SingleTotalInt256 intended; SingleTotalInt256 conjugate; } struct WalletOperatorHashes { bytes32 wallet; bytes32 operator; } struct Signature { bytes32 r; bytes32 s; uint8 v; } struct Seal { bytes32 hash; Signature signature; } struct WalletOperatorSeal { Seal wallet; Seal operator; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SettlementChallengeTypesLib * @dev Types for settlement challenges */ library SettlementChallengeTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- enum Status {Qualified, Disqualified} struct Proposal { address wallet; uint256 nonce; uint256 referenceBlockNumber; uint256 definitionBlockNumber; uint256 expirationTime; // Status Status status; // Amounts Amounts amounts; // Currency MonetaryTypesLib.Currency currency; // Info on challenged driip Driip challenged; // True is equivalent to reward coming from wallet's balance bool walletInitiated; // True if proposal has been terminated bool terminated; // Disqualification Disqualification disqualification; } struct Amounts { // Cumulative (relative) transfer info int256 cumulativeTransfer; // Stage info int256 stage; // Balances after amounts have been staged int256 targetBalance; } struct Driip { // Kind ("payment", "trade", ...) string kind; // Hash (of operator) bytes32 hash; } struct Disqualification { // Challenger address challenger; uint256 nonce; uint256 blockNumber; // Info on candidate driip Driip candidate; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NullSettlementChallengeState * @notice Where null settlements challenge state is managed */ contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal"; string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal"; string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal"; string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal"; // // Variables // ----------------------------------------------------------------------------------------------------------------- SettlementChallengeTypesLib.Proposal[] public proposals; mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the number of proposals /// @return The number of proposals function proposalsCount() public view returns (uint256) { return proposals.length; } /// @notice Initiate a proposal /// @param wallet The address of the concerned challenged wallet /// @param nonce The wallet nonce /// @param stageAmount The proposal stage amount /// @param targetBalanceAmount The proposal target balance amount /// @param currency The concerned currency /// @param blockNumber The proposal block number /// @param walletInitiated True if initiated by the concerned challenged wallet function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated) public onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION) { // Initiate proposal _initiateProposal( wallet, nonce, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated ); // Emit event emit InitiateProposalEvent( wallet, nonce, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function terminateProposal(address wallet, MonetaryTypesLib.Currency currency) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param walletTerminated True if wallet terminated function terminateProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated); // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function removeProposal(address wallet, MonetaryTypesLib.Currency currency) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); // Remove proposal _removeProposal(index); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param walletTerminated True if wallet terminated function removeProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated); // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); // Remove proposal _removeProposal(index); } /// @notice Disqualify a proposal /// @dev A call to this function will intentionally override previous disqualifications if existent /// @param challengedWallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param challengerWallet The address of the concerned challenger wallet /// @param blockNumber The disqualification block number /// @param candidateNonce The candidate nonce /// @param candidateHash The candidate hash /// @param candidateKind The candidate kind function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency currency, address challengerWallet, uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string candidateKind) public onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id]; require(0 != index); // Update proposal proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].disqualification.challenger = challengerWallet; proposals[index - 1].disqualification.nonce = candidateNonce; proposals[index - 1].disqualification.blockNumber = blockNumber; proposals[index - 1].disqualification.candidate.hash = candidateHash; proposals[index - 1].disqualification.candidate.kind = candidateKind; // Emit event emit DisqualifyProposalEvent( challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind ); } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposal(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { // 1-based index return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; } /// @notice Gauge whether the proposal for the given wallet and currency has terminated /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has terminated, else false function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].terminated; } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposalExpired(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return block.timestamp >= proposals[index - 1].expirationTime; } /// @notice Get the settlement proposal challenge nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal nonce function proposalNonce(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].nonce; } /// @notice Get the settlement proposal reference block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal reference block number function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].referenceBlockNumber; } /// @notice Get the settlement proposal definition block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal reference block number function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].definitionBlockNumber; } /// @notice Get the settlement proposal expiration time of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal expiration time function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].expirationTime; } /// @notice Get the settlement proposal status of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal status function proposalStatus(address wallet, MonetaryTypesLib.Currency currency) public view returns (SettlementChallengeTypesLib.Status) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].status; } /// @notice Get the settlement proposal stage amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal stage amount function proposalStageAmount(address wallet, MonetaryTypesLib.Currency currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].amounts.stage; } /// @notice Get the settlement proposal target balance amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal target balance amount function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].amounts.targetBalance; } /// @notice Get the settlement proposal balance reward of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal balance reward function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].walletInitiated; } /// @notice Get the settlement proposal disqualification challenger of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification challenger function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency currency) public view returns (address) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.challenger; } /// @notice Get the settlement proposal disqualification block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification block number function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.blockNumber; } /// @notice Get the settlement proposal disqualification nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification nonce function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.nonce; } /// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate hash function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency currency) public view returns (bytes32) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.candidate.hash; } /// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate kind function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency currency) public view returns (string) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.candidate.kind; } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 referenceBlockNumber, bool walletInitiated) private { // Require that stage and target balance amounts are positive require(stageAmount.isPositiveInt256()); require(targetBalanceAmount.isPositiveInt256()); uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Create proposal if needed if (0 == index) { index = ++(proposals.length); proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index; } // Populate proposal proposals[index - 1].wallet = wallet; proposals[index - 1].nonce = nonce; proposals[index - 1].referenceBlockNumber = referenceBlockNumber; proposals[index - 1].definitionBlockNumber = block.number; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified; proposals[index - 1].currency = currency; proposals[index - 1].amounts.stage = stageAmount; proposals[index - 1].amounts.targetBalance = targetBalanceAmount; proposals[index - 1].walletInitiated = walletInitiated; proposals[index - 1].terminated = false; } function _removeProposal(uint256 index) private returns (bool) { // Remove the proposal and clear references to it proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0; if (index < proposals.length) { proposals[index - 1] = proposals[proposals.length - 1]; proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index; } proposals.length--; } function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId) private view returns (int256 amount, uint256 blockNumber) { // Get last log record of deposited and settled balances (int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord( wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId ); (int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord( wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId ); // Set amount as the sum of deposited and settled amount = depositedAmount.add(settledAmount); // Set block number as the latest of deposited and settled blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber; } }
@notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount() public view returns (uint256) { return tradeTakerFeeByBlockNumber.count(); }
415,250
[ 1, 967, 1300, 434, 18542, 268, 6388, 14036, 1203, 1300, 11374, 414, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18542, 56, 6388, 2954, 281, 1380, 1435, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 18542, 56, 6388, 14667, 858, 1768, 1854, 18, 1883, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ██╗ ███████╗██╗ ██╗ ██║ ██╔════╝╚██╗██╔╝ ██║ █████╗ ╚███╔╝ ██║ ██╔══╝ ██╔██╗ ███████╗███████╗██╔╝ ██╗ ╚══════╝╚══════╝╚═╝ ╚═╝ ██╗ ██████╗ ██████╗██╗ ██╗███████╗██████╗ ██║ ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗ ██║ ██║ ██║██║ █████╔╝ █████╗ ██████╔╝ ██║ ██║ ██║██║ ██╔═██╗ ██╔══╝ ██╔══██╗ ███████╗╚██████╔╝╚██████╗██║ ██╗███████╗██║ ██║ ╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ DEAR MSG.SENDER(S): / LXL is a project in beta // Please audit & use at your own risk /// Entry into LXL shall not create an attorney/client relationship //// Likewise, LXL should not be construed as legal advice or replacement for professional counsel ///// STEAL THIS C0D3SL4W ~presented by LexDAO LLC \+|+/ */ // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.5; interface IERC20 { // brief interface for erc20 token function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 amount) external returns (bool); } library Address { // helper for address type - see 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; } } library SafeERC20 { // wrapper around erc20 token tx for non-standard contract - see openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol using Address for address; function safeTransfer(IERC20 token, address to, uint256 amount) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, amount)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, amount)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returnData) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returnData.length > 0) { // return data is optional require(abi.decode(returnData, (bool)), "SafeERC20: erc20 operation did not succeed"); } } } library SafeMath { // arithmetic wrapper for under/overflow check function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } } contract ReentrancyGuard { // call wrapper for reentrancy check - see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } /** * @title LexLocker. * @author LexDAO LLC. * @notice Token locker registry with embedded terms and resolution. */ contract LexLocker is ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; /*$<⚖️️> LXL <⚔️>$*/ address public manager; // account managing LXL settings - see 'Manager Functions' - updateable by manager address public swiftResolverToken; // token required to participate as swift resolver - updateable by manager address public userRewardToken; // token for LXL user rewards - updateable by manager address public wETH; // ether token wrapper contract reference - updateable by manager uint256 public lockerCount; // lockers counted into LXL registry uint256 public MAX_DURATION; // time limit in seconds on token lockup - default 63113904 (2-year) - updateable by manager uint256 public resolutionRate; // rate to determine resolution fee for disputed locker (e.g., 20 = 5% of remainder) - updateable by manager uint256 public swiftResolverTokenBalance; // balance required in `swiftResolverToken` to participate as swift resolver - updateable by manager uint256 public userReward; // reward amount granted to LXL users in `userRewardToken`- updateable by manager string public lockerTerms; // general terms wrapping LXL - updateable by manager string[] public marketTerms; // embedded market LXL terms - attach to locker `details` (e.g., "MT:1") - updateable by manager string[] public resolutions; // locker resolutions stamped by LXL resolvers mapping(address => uint256[]) private registrations; // tracks registered lockers per account (client/provider) mapping(address => bool) public swiftResolverRegistrations; // tracks registered swift resolvers mapping(uint256 => ADR) public adrs; // tracks ADR details for registered lockers mapping(uint256 => Locker) public lockers; // tracks registered lockers details event DepositLocker(address indexed client, address clientOracle, address indexed provider, address indexed resolver, address token, uint256[] amount, uint256 registration, uint256 sum, uint256 termination, string details, bool swiftResolver); event RegisterLocker(address indexed client, address clientOracle, address indexed provider, address indexed resolver, address token, uint256[] amount, uint256 registration, uint256 sum, uint256 termination, string details, bool swiftResolver); event ConfirmLocker(uint256 registration); event RequestLockerResolution(address indexed client, address indexed counterparty, address indexed resolver, address token, uint256 registration, uint256 sum, string details, bool swiftResolver); event Release(uint256 milestone, uint256 payment, uint256 registration); event Withdraw(uint256 registration); event AssignClientOracle(address indexed clientOracle, uint256 registration); event ClientProposeResolver(address indexed proposedResolver, uint256 registration, string details); event ProviderProposeResolver(address indexed proposedResolver, uint256 registration, string details); event UpdateSwiftResolverStatus(address indexed swiftResolver, string details, bool registered); event Lock(address indexed caller, uint256 registration, string details); event Resolve(address indexed resolver, uint256 clientAward, uint256 providerAward, uint256 registration, uint256 resolutionFee, string resolution); event AddMarketTerms(uint256 index, string terms); event AmendMarketTerms(uint256 index, string terms); event UpdateLockerSettings(address indexed manager, address swiftResolverToken, address userRewardToken, address wETH, uint256 MAX_DURATION, uint256 resolutionRate, uint256 swiftResolverTokenBalance, uint256 userReward, string lockerTerms); event TributeToManager(address indexed caller, uint256 amount, string details); struct ADR { address proposedResolver; address resolver; uint8 clientProposedResolver; uint8 providerProposedResolver; uint256 clientAward; uint256 providerAward; uint256 resolutionRate; string resolution; bool swiftResolver; } struct Locker { address client; address clientOracle; address provider; address token; uint8 confirmed; uint8 locked; uint256[] amount; uint256 currentMilestone; uint256 milestones; uint256 released; uint256 sum; uint256 termination; string details; } constructor( address _manager, address _swiftResolverToken, address _userRewardToken, address _wETH, uint256 _MAX_DURATION, uint256 _resolutionRate, uint256 _swiftResolverTokenBalance, uint256 _userReward, string memory _lockerTerms ) { require(_resolutionRate > 0, "_resolutionRate < 1"); manager = _manager; swiftResolverToken = _swiftResolverToken; userRewardToken = _userRewardToken; wETH = _wETH; MAX_DURATION = _MAX_DURATION; resolutionRate = _resolutionRate; swiftResolverTokenBalance = _swiftResolverTokenBalance; userReward = _userReward; lockerTerms = _lockerTerms; } /*************** LOCKER FUNCTIONS ***************/ // ************ // REGISTRATION // ************ /** * @notice LXL can be registered as deposit from `client` for benefit of `provider`. * @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call. * @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure). * @param provider Account to receive registered `amount`s. * @param resolver Account that can call `resolve()` to award `sum` remainder between LXL parties. * @param token Token address for `amount` deposit. * @param amount Array of milestone `amount`s to be sent to `provider` on call of `release()`. * @param termination Exact `termination` date in seconds since epoch. * @param details Context re: LXL. * @param swiftResolver If `true`, `sum` remainder can be resolved by holders of `swiftResolverToken`. */ function depositLocker( // CLIENT-TRACK address clientOracle, address provider, address resolver, address token, uint256[] calldata amount, uint256 termination, string memory details, bool swiftResolver ) external nonReentrant payable returns (uint256) { require(msg.sender != resolver && clientOracle != resolver && provider != resolver, "client/clientOracle/provider = resolver"); require(termination <= block.timestamp.add(MAX_DURATION), "duration maxed"); uint256 sum; for (uint256 i = 0; i < amount.length; i++) { sum = sum.add(amount[i]); } if (msg.value > 0) { address weth = wETH; require(token == weth && msg.value == sum, "!ethBalance"); (bool success, ) = weth.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(weth).transfer(address(this), msg.value); } else { IERC20(token).safeTransferFrom(msg.sender, address(this), sum); } lockerCount++; uint256 registration = lockerCount; registrations[msg.sender].push(registration); registrations[provider].push(registration); adrs[registration] = ADR( address(0), resolver, 0, 0, 0, 0, resolutionRate, "", swiftResolver); lockers[registration] = Locker( msg.sender, clientOracle, provider, token, 1, 0, amount, 1, amount.length, 0, sum, termination, details); if (userReward > 0) {IERC20(userRewardToken).transfer(msg.sender, userReward);} // grant LXL user reward emit DepositLocker(msg.sender, clientOracle, provider, resolver, token, amount, registration, sum, termination, details, swiftResolver); return registration; } /** * @notice LXL can be registered as single deposit (lump sum) from `client` for benefit of `provider`. * @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call. * @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure). * @param provider Account to receive registered `amount`s. * @param resolver Account that can call `resolve()` to award `sum` remainder between LXL parties. * @param token Token address for `amount` deposit. * @param sum Lump `sum` to be sent to `provider` on call of `release()`. * @param termination Exact `termination` date in seconds since epoch. * @param details Context re: LXL. * @param swiftResolver If `true`, `sum` remainder can be resolved by holders of `swiftResolverToken`. */ function depositLockerSingleMilestone( // CLIENT-TRACK address clientOracle, address provider, address resolver, address token, uint256 sum, uint256 termination, string calldata details, bool swiftResolver ) external nonReentrant payable returns (uint256) { require(msg.sender != resolver && clientOracle != resolver && provider != resolver, "client/clientOracle/provider = resolver"); require(termination <= block.timestamp.add(MAX_DURATION), "duration maxed"); if (msg.value > 0) { address weth = wETH; require(token == weth && msg.value == sum, "!ethBalance"); (bool success, ) = weth.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(weth).transfer(address(this), msg.value); } else { IERC20(token).safeTransferFrom(msg.sender, address(this), sum); } uint256[] memory amount = new uint256[](1); amount[0] = sum; lockerCount++; uint256 registration = lockerCount; registrations[msg.sender].push(registration); registrations[provider].push(registration); adrs[registration] = ADR( address(0), resolver, 0, 0, 0, 0, resolutionRate, "", swiftResolver); lockers[registration] = Locker( msg.sender, clientOracle, provider, token, 1, 0, amount, 1, 1, 0, sum, termination, details); if (userReward > 0) {IERC20(userRewardToken).transfer(msg.sender, userReward);} // grant LXL user reward emit DepositLocker(msg.sender, clientOracle, provider, resolver, token, amount, registration, sum, termination, details, swiftResolver); return registration; } /** * @notice LXL can be registered as `provider` request for `client` deposit (by calling `confirmLocker()`). * @param client Account to provide `sum` deposit and call `release()` of registered `amount`s. * @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure). * @param provider Account to receive registered `amount`s. * @param resolver Account that can call `resolve()` to award `sum` remainder between LXL parties. * @param token Token address for `amount` deposit. * @param amount Array of milestone `amount`s to be sent to `provider` on call of `release()`. * @param termination Exact `termination` date in seconds since epoch. * @param details Context re: LXL. * @param swiftResolver If `true`, `sum` remainder can be resolved by holders of `swiftResolverToken`. */ function registerLocker( // PROVIDER-TRACK address client, address clientOracle, address provider, address resolver, address token, uint256[] calldata amount, uint256 termination, string memory details, bool swiftResolver ) external nonReentrant returns (uint256) { require(client != resolver && clientOracle != resolver && provider != resolver, "client/clientOracle/provider = resolver"); require(termination <= block.timestamp.add(MAX_DURATION), "duration maxed"); uint256 sum; for (uint256 i = 0; i < amount.length; i++) { sum = sum.add(amount[i]); } lockerCount++; uint256 registration = lockerCount; registrations[client].push(registration); registrations[provider].push(registration); adrs[registration] = ADR( address(0), resolver, 0, 0, 0, 0, resolutionRate, "", swiftResolver); lockers[registration] = Locker( client, clientOracle, provider, token, 0, 0, amount, 1, amount.length, 0, sum, termination, details); if (userReward > 0) {IERC20(userRewardToken).transfer(msg.sender, userReward);} // grant LXL user reward emit RegisterLocker(client, clientOracle, provider, resolver, token, amount, registration, sum, termination, details, swiftResolver); return registration; } /** * @notice LXL `client` can confirm after `registerLocker()` is called to deposit `sum` for `provider`. * @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call. * @param registration Registered LXL number. */ function confirmLocker(uint256 registration) external nonReentrant payable { // PROVIDER-TRACK Locker storage locker = lockers[registration]; require(msg.sender == locker.client, "!client"); require(locker.confirmed == 0, "confirmed"); if (msg.value > 0) { address weth = wETH; require(locker.token == weth && msg.value == locker.sum, "!ethBalance"); (bool success, ) = weth.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(weth).transfer(address(this), msg.value); } else { IERC20(locker.token).safeTransferFrom(msg.sender, address(this), locker.sum); } locker.confirmed = 1; emit ConfirmLocker(registration); } /** * @notice LXL depositor (`client`) can request direct resolution between selected `counterparty` over `sum`. E.g., staked wager to benefit charity as `counterparty`. * @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call. * @param counterparty Other account (`provider`) that can receive award from `resolver`. * @param resolver Account that can call `resolve()` to award `sum` between LXL parties. * @param token Token address for `sum`. * @param sum Lump `sum` amount for resolution. * @param details Context re: resolution request. * @param swiftResolver If `true`, `sum` can be resolved by holders of `swiftResolverToken`. */ function requestLockerResolution(address counterparty, address resolver, address token, uint256 sum, string calldata details, bool swiftResolver) external nonReentrant payable returns (uint256) { require(msg.sender != resolver && counterparty != resolver, "client/counterparty = resolver"); if (msg.value > 0) { address weth = wETH; require(token == weth && msg.value == sum, "!ethBalance"); (bool success, ) = weth.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(weth).transfer(address(this), msg.value); } else { IERC20(token).safeTransferFrom(msg.sender, address(this), sum); } uint256[] memory amount = new uint256[](1); amount[0] = sum; lockerCount++; uint256 registration = lockerCount; registrations[msg.sender].push(registration); registrations[counterparty].push(registration); adrs[registration] = ADR( address(0), resolver, 0, 0, 0, 0, resolutionRate, "", swiftResolver); lockers[registration] = Locker( msg.sender, address(0), counterparty, token, 1, 1, amount, 0, 0, 0, sum, 0, details); if (userReward > 0) {IERC20(userRewardToken).transfer(msg.sender, userReward);} // grant LXL user reward emit RequestLockerResolution(msg.sender, counterparty, resolver, token, registration, sum, details, swiftResolver); return registration; } // *********** // CLIENT MGMT // *********** /** * @notice LXL `client` can assign account as `clientOracle` to help call `release()` and `withdraw()`. * @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure). * @param registration Registered LXL number. */ function assignClientOracle(address clientOracle, uint256 registration) external nonReentrant { ADR storage adr = adrs[registration]; Locker storage locker = lockers[registration]; require(msg.sender == locker.client, "!client"); require(clientOracle != adr.resolver, "clientOracle = resolver"); require(locker.locked == 0, "locked"); require(locker.released < locker.sum, "released"); locker.clientOracle = clientOracle; emit AssignClientOracle(clientOracle, registration); } /** * @notice LXL `client` or `clientOracle` can release milestone `amount` to `provider`. * @param registration Registered LXL number. */ function release(uint256 registration) external nonReentrant { Locker storage locker = lockers[registration]; uint256 milestone = locker.currentMilestone-1; uint256 payment = locker.amount[milestone]; uint256 released = locker.released; uint256 sum = locker.sum; require(msg.sender == locker.client || msg.sender == locker.clientOracle, "!client/oracle"); require(locker.confirmed == 1, "!confirmed"); require(locker.locked == 0, "locked"); require(released < sum, "released"); IERC20(locker.token).safeTransfer(locker.provider, payment); locker.released = released.add(payment); if (locker.released < sum) {locker.currentMilestone++;} emit Release(milestone+1, payment, registration); } /** * @notice LXL `client` or `clientOracle` can withdraw `sum` remainder after `termination`. * @dev `release()` can still be called by `client` or `clientOracle` after `termination` to preserve extension option. * @param registration Registered LXL number. */ function withdraw(uint256 registration) external nonReentrant { Locker storage locker = lockers[registration]; address client = locker.client; uint256 released = locker.released; uint256 sum = locker.sum; require(msg.sender == client || msg.sender == locker.clientOracle, "!client/oracle"); require(locker.confirmed == 1, "!confirmed"); require(locker.locked == 0, "locked"); require(released < sum, "released"); require(locker.termination < block.timestamp, "!terminated"); IERC20(locker.token).safeTransfer(client, sum.sub(released)); locker.released = sum; emit Withdraw(registration); } // ********** // RESOLUTION // ********** /** * @notice LXL `client` or `provider` can lock to freeze release and withdrawal of `sum` remainder until `resolver` calls `resolve()`. * @dev `lock()` can be called repeatedly to allow LXL parties to continue to provide context until resolution. * @param registration Registered LXL number. * @param details Context re: lock / dispute. */ function lock(uint256 registration, string calldata details) external nonReentrant { Locker storage locker = lockers[registration]; require(msg.sender == locker.client || msg.sender == locker.provider, "!party"); require(locker.confirmed == 1, "!confirmed"); require(locker.released < locker.sum, "released"); locker.locked = 1; emit Lock(msg.sender, registration, details); } /** * @notice After LXL is locked, selected `resolver` awards `sum` remainder between `client` and `provider` minus fee. * @param clientAward Remainder awarded to `client`. * @param providerAward Remainder awarded to `provider`. * @param registration Registered LXL number. * @param resolution Context re: resolution. */ function resolve(uint256 clientAward, uint256 providerAward, uint256 registration, string calldata resolution) external nonReentrant { ADR storage adr = adrs[registration]; Locker storage locker = lockers[registration]; address token = locker.token; uint256 released = locker.released; uint256 sum = locker.sum; // calculate resolution fee as set on registration: uint256 remainder = sum.sub(released); uint256 resolutionFee = remainder.div(adr.resolutionRate); require(locker.locked == 1, "!locked"); require(released < sum, "released"); require(clientAward.add(providerAward) == remainder.sub(resolutionFee), "awards != remainder - fee"); if (adr.swiftResolver) { require(msg.sender != locker.client && msg.sender != locker.provider, "client/provider = swiftResolver"); require(IERC20(swiftResolverToken).balanceOf(msg.sender) >= swiftResolverTokenBalance && swiftResolverRegistrations[msg.sender], "!swiftResolverTokenBalance/registered"); } else { require(msg.sender == adr.resolver, "!resolver"); } IERC20(token).safeTransfer(msg.sender, resolutionFee); IERC20(token).safeTransfer(locker.client, clientAward); IERC20(token).safeTransfer(locker.provider, providerAward); adr.clientAward = clientAward; adr.providerAward = providerAward; adr.resolution = resolution; locker.released = sum; resolutions.push(resolution); emit Resolve(msg.sender, clientAward, providerAward, registration, resolutionFee, resolution); } /** * @notice Fallback to allow LXL party to suggest new `resolver` to counterparty. * @dev LXL `client` calls to update `resolver` selection - if matches `provider` suggestion or confirmed, `resolver` updates. * @param proposedResolver Proposed account to resolve LXL. * @param registration Registered LXL number. * @param details Context re: proposed `resolver`. */ function clientProposeResolver(address proposedResolver, uint256 registration, string calldata details) external nonReentrant { ADR storage adr = adrs[registration]; Locker storage locker = lockers[registration]; require(msg.sender == locker.client, "!client"); require(msg.sender != proposedResolver && locker.clientOracle != proposedResolver && locker.provider != proposedResolver, "client/clientOracle/provider = proposedResolver"); require(adr.clientProposedResolver == 0, "pending"); require(locker.released < locker.sum, "released"); if (adr.proposedResolver == proposedResolver) { adr.resolver = proposedResolver; } adr.proposedResolver = proposedResolver; adr.clientProposedResolver = 1; adr.providerProposedResolver = 0; emit ClientProposeResolver(proposedResolver, registration, details); } /** * @notice Fallback to allow LXL party to suggest new `resolver` to counterparty. * @dev LXL `provider` calls to update `resolver` selection - if matches `client` suggestion or confirmed, `resolver` updates. * @param proposedResolver Proposed account to resolve LXL. * @param registration Registered LXL number. * @param details Context re: proposed `resolver`. */ function providerProposeResolver(address proposedResolver, uint256 registration, string calldata details) external nonReentrant { ADR storage adr = adrs[registration]; Locker storage locker = lockers[registration]; require(msg.sender == locker.provider, "!provider"); require(locker.client != proposedResolver && locker.clientOracle != proposedResolver && msg.sender != proposedResolver, "client/clientOracle/provider = proposedResolver"); require(adr.providerProposedResolver == 0, "pending"); require(locker.released < locker.sum, "released"); if (adr.proposedResolver == proposedResolver) { adr.resolver = proposedResolver; } adr.proposedResolver = proposedResolver; adr.clientProposedResolver = 0; adr.providerProposedResolver = 1; emit ProviderProposeResolver(proposedResolver, registration, details); } /** * @notice Swift resolvers call to update LXL service status. * @dev Swift resolvers must first confirm to participate and can continue with details / cancel LXL service. * @param details Context re: status update. * @param registered If `true`, swift resolver can participate in LXL resolution. */ function updateSwiftResolverStatus(string calldata details, bool registered) external nonReentrant { require(IERC20(swiftResolverToken).balanceOf(msg.sender) >= swiftResolverTokenBalance, "!swiftResolverTokenBalance"); swiftResolverRegistrations[msg.sender] = registered; emit UpdateSwiftResolverStatus(msg.sender, details, registered); } // ******* // GETTERS // ******* function latestLockerRegistration(address account) external view returns (uint256 latest) { // get latest registered locker per account uint256[] memory registered = registrations[account]; if (registered.length == 0) {return 0;} else {return registered[registered.length-1];} } function lockerRegistrations(address account) external view returns (uint256[] memory registered) { // get registered lockers per account return registrations[account]; } function marketTermsCount() external view returns (uint256 count) { // get total market terms stamped by `manager` return marketTerms.length; } function providerAmounts(uint256 registration) external view returns (address token, uint256[] memory amount) { // get `token` and milestone `amount`s for `provider` return (lockers[registration].token, lockers[registration].amount); } function resolutionsCount() external view returns (uint256 count) { // get total resolutions passed by LXL `resolver`s return resolutions.length; } /**************** MANAGER FUNCTIONS ****************/ /** * @dev Throws if caller is not LXL `manager`. */ modifier onlyManager { require(msg.sender == manager, "!manager"); _; } /** * @notice Updates LXL with new market `terms`. * @param terms New `terms` to add to LXL market. */ function addMarketTerms(string calldata terms) external nonReentrant onlyManager { marketTerms.push(terms); emit AddMarketTerms(marketTerms.length-1, terms); } /** * @notice Updates LXL with amended market `terms`. * @param index Targeted location in `marketTerms` array. * @param terms Amended `terms` to add to LXL market. */ function amendMarketTerms(uint256 index, string calldata terms) external nonReentrant onlyManager { marketTerms[index] = terms; emit AmendMarketTerms(index, terms); } /** * @notice General ether payment function for `manager` of LXL contract. * @param details Describes context for ether transfer. */ function tributeToManager(string calldata details) external nonReentrant payable { (bool success, ) = manager.call{value: msg.value}(""); require(success, "!ethCall"); emit TributeToManager(msg.sender, msg.value, details); } /** * @notice Updates LXL management settings. * @param _manager Account that governs LXL contract settings. * @param _swiftResolverToken Token to mark participants in swift resolution. * @param _userRewardToken Token for LXL user rewards. * @param _wETH Standard contract reference to wrap ether. * @param _MAX_DURATION Time limit in seconds on token lockup - default 63113904 (2-year). * @param _resolutionRate Rate to determine resolution fee for locker (e.g., 20 = 5% of remainder). * @param _swiftResolverTokenBalance Token balance required to perform swift resolution. * @param _userReward Reward amount granted to LXL users in `userRewardToken`. * @param _lockerTerms General terms wrapping LXL. */ function updateLockerSettings( address _manager, address _swiftResolverToken, address _userRewardToken, address _wETH, uint256 _MAX_DURATION, uint256 _resolutionRate, uint256 _swiftResolverTokenBalance, uint256 _userReward, string calldata _lockerTerms ) external nonReentrant onlyManager { require(_resolutionRate > 0, "_resolutionRate < 1"); manager = _manager; swiftResolverToken = _swiftResolverToken; userRewardToken = _userRewardToken; wETH = _wETH; MAX_DURATION = _MAX_DURATION; resolutionRate = _resolutionRate; swiftResolverTokenBalance = _swiftResolverTokenBalance; userReward = _userReward; lockerTerms = _lockerTerms; emit UpdateLockerSettings(_manager, _swiftResolverToken, _userRewardToken, _wETH, _MAX_DURATION, _resolutionRate, _swiftResolverTokenBalance, _userReward, _lockerTerms); } }
get registered lockers per account
function lockerRegistrations(address account) external view returns (uint256[] memory registered) {
264,059
[ 1, 588, 4104, 2176, 414, 1534, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 28152, 20175, 1012, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 4104, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Dependency file: contracts/interfaces/ISetValuer.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ // pragma solidity 0.6.10; // import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } // Dependency file: contracts/interfaces/IPriceOracle.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } // Dependency file: contracts/interfaces/IIntegrationRegistry.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "./IERC20.sol"; // import "../../math/SafeMath.sol"; // import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: contracts/protocol/lib/ResourceIdentifier.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // import { IController } from "../../interfaces/IController.sol"; // import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; // import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; // import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // Dependency file: contracts/interfaces/IModule.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } // Dependency file: contracts/lib/ExplicitERC20.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency 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; } } // Dependency file: contracts/lib/PreciseUnitMath.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // pragma experimental ABIEncoderV2; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // Dependency file: contracts/protocol/lib/Position.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); addExternalPosition(_setToken, _component, _module, _newUnit, _data); } else if (!_setToken.isExternalPositionModule(_component, _module)) { addExternalPosition(_setToken, _component, _module, _newUnit, _data); } else if (_newUnit != 0) { _setToken.editExternalPositionUnit(_component, _module, _newUnit); } else { // If no default or external position remaining then remove component from components array if (_setToken.getDefaultPositionRealUnit(_component) == 0 && _setToken.getExternalPositionModules(_component).length == 1) { _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } /** * Add a new external position from a previously untracked module. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function addExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { _setToken.addExternalPositionModule(_component, _module); _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units if (_preTotalNotional >= _postTotalNotional) { uint256 unitsToSub = _preTotalNotional.sub(_postTotalNotional).preciseDivCeil(_setTokenSupply); return _prePositionUnit.sub(unitsToSub); } else { // Else subtract post action total notional from pre action total notional and calculate new position units uint256 unitsToAdd = _postTotalNotional.sub(_preTotalNotional).preciseDiv(_setTokenSupply); return _prePositionUnit.add(unitsToAdd); } } } // Dependency file: contracts/protocol/lib/ModuleBase.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; // import { IController } from "../../interfaces/IController.sol"; // import { IModule } from "../../interfaces/IModule.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { Invoke } from "./Invoke.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; // import { ResourceIdentifier } from "./ResourceIdentifier.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. */ abstract contract ModuleBase is IModule { using PreciseUnitMath for uint256; using Invoke for ISetToken; using ResourceIdentifier for IController; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } } // Dependency file: contracts/interfaces/external/IUniswapV2Router.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; interface IUniswapV2Router { 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); } // Dependency file: contracts/interfaces/external/IUniswapV2Pair.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License */ // pragma solidity 0.6.10; 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; } // Dependency file: contracts/interfaces/external/IStakingRewards.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; } // Dependency file: contracts/interfaces/ISetToken.sol // Dependency 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); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // Dependency file: contracts/protocol/lib/Invoke.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } // Dependency file: contracts/interfaces/IController.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol // pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Dependency 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; } } // Dependency file: @openzeppelin/contracts/utils/SafeCast.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // Dependency 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; } } // Dependency 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); } } // Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol // pragma solidity ^0.6.0; // import "../../GSN/Context.sol"; // import "./IERC20.sol"; // import "../../math/SafeMath.sol"; // import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; // import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { Math } from "@openzeppelin/contracts/math/Math.sol"; // import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; // import { IController } from "../../interfaces/IController.sol"; // import { Invoke } from "../lib/Invoke.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { IStakingRewards } from "../../interfaces/external/IStakingRewards.sol"; // import { IUniswapV2Pair } from "../../interfaces/external/IUniswapV2Pair.sol"; // import { IUniswapV2Router } from "../../interfaces/external/IUniswapV2Router.sol"; // import { ModuleBase } from "../lib/ModuleBase.sol"; // import { Position } from "../lib/Position.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; contract UniswapYieldStrategy is ModuleBase, ReentrancyGuard { using Position for ISetToken; using Invoke for ISetToken; using SafeMath for uint256; using SafeCast for uint256; using SafeCast for int256; /* ============ State Variables ============ */ IUniswapV2Router public uniswapRouter; IUniswapV2Pair public lpToken; IERC20 public assetOne; IERC20 public assetTwo; IERC20 public uni; address public feeRecipient; IStakingRewards public rewarder; ISetToken public setToken; uint256 public reservePercentage; // Precise percentage (e.g. 10^16 = 1%) uint256 public slippageTolerance; // Precise percentage uint256 public rewardFee; // Precise percentage uint256 public withdrawalFee; // Precise percentage uint256 public assetOneBaseUnit; uint256 public assetTwoBaseUnit; uint256 public lpTokenBaseUnit; /* ============ Constructor ============ */ constructor( IController _controller, IUniswapV2Router _uniswapRouter, IUniswapV2Pair _lpToken, IERC20 _assetOne, IERC20 _assetTwo, IERC20 _uni, IStakingRewards _rewarder, address _feeRecipient ) public ModuleBase(_controller) { controller = _controller; uniswapRouter = _uniswapRouter; lpToken = _lpToken; assetOne = _assetOne; assetTwo = _assetTwo; uni = _uni; rewarder = _rewarder; feeRecipient = _feeRecipient; uint256 tokenOneDecimals = ERC20(address(_assetOne)).decimals(); assetOneBaseUnit = 10 ** tokenOneDecimals; uint256 tokenTwoDecimals = ERC20(address(_assetTwo)).decimals(); assetTwoBaseUnit = 10 ** tokenTwoDecimals; uint256 lpTokenDecimals = ERC20(address(_lpToken)).decimals(); lpTokenBaseUnit = 10 ** lpTokenDecimals; } /* ============ External Functions ============ */ function engage() external nonReentrant { _engage(); } function disengage() external nonReentrant { _rebalance(0); uint256 lpTokenQuantity = _calculateDisengageLPQuantity(); _unstake(lpTokenQuantity); _approveAndRemoveLiquidity(lpTokenQuantity); _updatePositions(); } function reap() external nonReentrant { _handleReward(); _engage(); } function rebalance() external nonReentrant { _rebalance(0); _updatePositions(); } function rebalanceSome(uint256 _sellTokenQuantity) external nonReentrant { _rebalance(_sellTokenQuantity); _updatePositions(); } function unstakeAndRedeem(uint256 _setTokenQuantity) external nonReentrant { require(setToken.balanceOf(msg.sender) >= _setTokenQuantity, "User must have sufficient SetToken"); setToken.burn(msg.sender, _setTokenQuantity); uint256 lpTokenUnit = setToken.getExternalPositionRealUnit(address(lpToken), address(this)).toUint256(); uint256 userLPBalance = lpTokenUnit.preciseMul(_setTokenQuantity); _unstake(userLPBalance); uint256 lpFees = userLPBalance.preciseMul(withdrawalFee); setToken.invokeTransfer(address(lpToken), msg.sender, userLPBalance.sub(lpFees)); setToken.invokeTransfer(address(lpToken), feeRecipient, lpFees); uint256 assetOneUnit = setToken.getDefaultPositionRealUnit(address(assetOne)).toUint256(); uint256 assetOneNotional = assetOneUnit.preciseMul(_setTokenQuantity); uint256 assetOneFee = assetOneNotional.preciseMul(withdrawalFee); setToken.invokeTransfer(address(assetOne), msg.sender, assetOneNotional.sub(assetOneFee)); setToken.invokeTransfer(address(assetOne), feeRecipient, assetOneFee); uint256 assetTwoUnit = setToken.getDefaultPositionRealUnit(address(assetTwo)).toUint256(); uint256 assetTwoNotional = assetTwoUnit.preciseMul(_setTokenQuantity); uint256 assetTwoFee = assetTwoNotional.preciseMul(withdrawalFee); setToken.invokeTransfer(address(assetTwo), msg.sender, assetTwoNotional.sub(assetTwoFee)); setToken.invokeTransfer(address(assetTwo), feeRecipient, assetTwoFee); } function initialize( ISetToken _setToken, uint256 _reservePercentage, uint256 _slippageTolerance, uint256 _rewardFee, uint256 _withdrawalFee ) external onlySetManager(_setToken, msg.sender) { require(address(setToken) == address(0), "May only be called once"); setToken = _setToken; reservePercentage = _reservePercentage; slippageTolerance = _slippageTolerance; rewardFee = _rewardFee; withdrawalFee = _withdrawalFee; _setToken.initializeModule(); } function removeModule() external override { require(msg.sender == address(setToken), "Caller must be SetToken"); uint256 lpBalance = rewarder.balanceOf(address(setToken)); _unstake(lpBalance); _approveAndRemoveLiquidity(lpBalance); _updatePositions(); } /* ============ Internal Functions ============ */ function _engage() internal { _rebalance(0); (uint256 assetOneQuantity, uint256 assetTwoQuantity) = _calculateEngageQuantities(); uint256 lpBalance = _approveAndAddLiquidity(assetOneQuantity, assetTwoQuantity); _approveAndStake(lpBalance); _updatePositions(); } // Rebalances reserve assets to achieve a 50/50 value split // If a sellTokenQuantity is provided, then use this value function _rebalance(uint256 _sellTokenQuantity) internal { address assetToSell; address assetToBuy; uint256 quantityToSell; uint256 minimumBuyToken; uint256 assetOneToTwoPrice = controller.getPriceOracle().getPrice(address(assetOne), address(assetTwo)); uint256 balanceAssetOne = assetOne.balanceOf(address(setToken)); uint256 balanceAssetTwo = assetTwo.balanceOf(address(setToken)); // Convert Asset Two to One adjust for decimal differences uint256 valueAssetTwoDenomOne = balanceAssetTwo.preciseDiv(assetOneToTwoPrice).mul(assetOneBaseUnit).div(assetTwoBaseUnit); if (balanceAssetOne > valueAssetTwoDenomOne) { assetToSell = address(assetOne); assetToBuy = address(assetTwo); quantityToSell = balanceAssetOne.sub(valueAssetTwoDenomOne).div(2); // Base unit calculations are to normalize the values for different decimals minimumBuyToken = quantityToSell.preciseMul(assetOneToTwoPrice).mul(assetTwoBaseUnit).div(assetOneBaseUnit); } else { assetToSell = address(assetTwo); assetToBuy = address(assetOne); quantityToSell = valueAssetTwoDenomOne .sub(balanceAssetOne).div(2).preciseMul(assetOneToTwoPrice) .mul(assetTwoBaseUnit).div(assetOneBaseUnit); minimumBuyToken = quantityToSell.preciseDiv(assetOneToTwoPrice).mul(assetOneBaseUnit).div(assetTwoBaseUnit); } if (_sellTokenQuantity > 0) { require(_sellTokenQuantity <= quantityToSell, "Delta must be less than max"); minimumBuyToken = minimumBuyToken.preciseMul(_sellTokenQuantity).preciseDiv(quantityToSell); quantityToSell = _sellTokenQuantity; } // Reduce the expected receive quantity minimumBuyToken = minimumBuyToken .preciseMul(PreciseUnitMath.preciseUnit().sub(slippageTolerance)); setToken.invokeApprove(assetToSell, address(uniswapRouter), quantityToSell); if (quantityToSell > 0) { _invokeUniswapTrade(assetToSell, assetToBuy, quantityToSell, minimumBuyToken); } } function _approveAndAddLiquidity(uint256 _assetOneQuantity, uint256 _assetTwoQuantity) internal returns (uint256) { setToken.invokeApprove(address(assetOne), address(uniswapRouter), _assetOneQuantity); setToken.invokeApprove(address(assetTwo), address(uniswapRouter), _assetTwoQuantity); bytes memory addLiquidityBytes = abi.encodeWithSignature( "addLiquidity(address,address,uint256,uint256,uint256,uint256,address,uint256)", assetOne, assetTwo, _assetOneQuantity, _assetTwoQuantity, 1, 1, address(setToken), now.add(60) // Valid for one minute ); setToken.invoke(address(uniswapRouter), 0, addLiquidityBytes); return lpToken.balanceOf(address(setToken)); } function _approveAndRemoveLiquidity(uint256 _liquidityQuantity) internal { setToken.invokeApprove(address(lpToken), address(uniswapRouter), _liquidityQuantity); bytes memory removeLiquidityBytes = abi.encodeWithSignature( "removeLiquidity(address,address,uint256,uint256,uint256,address,uint256)", assetOne, assetTwo, _liquidityQuantity, 1, 1, address(setToken), now.add(60) // Valid for one minute ); setToken.invoke(address(uniswapRouter), 0, removeLiquidityBytes); } function _approveAndStake(uint256 _lpTokenQuantity) internal { setToken.invokeApprove(address(lpToken), address(rewarder), _lpTokenQuantity); bytes memory stakeBytes = abi.encodeWithSignature("stake(uint256)", _lpTokenQuantity); setToken.invoke(address(rewarder), 0, stakeBytes); } function _unstake(uint256 _lpTokenQuantity) internal { bytes memory unstakeBytes = abi.encodeWithSignature("withdraw(uint256)", _lpTokenQuantity); setToken.invoke(address(rewarder), 0, unstakeBytes); } function _handleReward() internal { setToken.invoke(address(rewarder), 0, abi.encodeWithSignature("getReward()")); uint256 uniBalance = uni.balanceOf(address(setToken)); uint256 assetOneBalance = assetOne.balanceOf(address(setToken)); setToken.invokeApprove(address(uni), address(uniswapRouter), uniBalance); _invokeUniswapTrade(address(uni), address(assetOne), uniBalance, 1); uint256 postTradeAssetOneBalance = assetOne.balanceOf(address(setToken)); uint256 fee = postTradeAssetOneBalance.sub(assetOneBalance).preciseMul(rewardFee); setToken.strictInvokeTransfer(address(assetOne), feeRecipient, fee); } function _invokeUniswapTrade( address _sellToken, address _buyToken, uint256 _amountIn, uint256 _amountOutMin ) internal { address[] memory path = new address[](2); path[0] = _sellToken; path[1] = _buyToken; bytes memory tradeBytes = abi.encodeWithSignature( "swapExactTokensForTokens(uint256,uint256,address[],address,uint256)", _amountIn, _amountOutMin, path, address(setToken), now.add(180) ); setToken.invoke(address(uniswapRouter), 0, tradeBytes); } function _calculateEngageQuantities() internal view returns(uint256 tokenAQuantity, uint256 tokenBQuantity) { ( uint256 desiredAssetOne, uint256 desiredAssetTwo, uint256 assetOneOnSetToken, uint256 assetTwoOnSetToken ) = _getDesiredSingleAssetReserve(); require(assetOneOnSetToken > desiredAssetOne && assetTwoOnSetToken > desiredAssetTwo, "SetToken assets must be > desired"); return ( assetOneOnSetToken.sub(desiredAssetOne), assetTwoOnSetToken.sub(desiredAssetTwo) ); } function _calculateDisengageLPQuantity() internal view returns(uint256 _lpTokenQuantity) { (uint256 assetOneToLPRate, uint256 assetTwoToLPRate) = _getLPReserveExchangeRate(); ( uint256 desiredOne, uint256 desiredTwo, uint256 assetOneOnSetToken, uint256 assetTwoOnSetToken ) = _getDesiredSingleAssetReserve(); require(assetOneOnSetToken < desiredOne && assetTwoOnSetToken < desiredTwo, "SetToken assets must be < desired"); // LP Rates already account for decimals uint256 minLPForOneToRedeem = desiredOne.sub(assetOneOnSetToken).preciseDiv(assetOneToLPRate); uint256 minLPForTwoToRedeem = desiredTwo.sub(assetTwoOnSetToken).preciseDiv(assetTwoToLPRate); return Math.max(minLPForOneToRedeem, minLPForTwoToRedeem); } // Returns desiredOneReserve, desiredTwoReserve, tokenOne and tokenTwo balances function _getDesiredSingleAssetReserve() internal view returns(uint256, uint256, uint256, uint256) { (uint256 assetOneReserve, uint256 assetTwoReserve) = _getTotalLPReserves(); uint256 balanceAssetOne = assetOne.balanceOf(address(setToken)); uint256 balanceAssetTwo = assetTwo.balanceOf(address(setToken)); uint256 desiredOneReserve = assetOneReserve.add(balanceAssetOne).preciseMul(reservePercentage); uint256 desiredTwoReserve = assetTwoReserve.add(balanceAssetTwo).preciseMul(reservePercentage); return(desiredOneReserve, desiredTwoReserve, balanceAssetOne, balanceAssetTwo); } // Returns assetAToLPRate and assetBToLPRate function _getLPReserveExchangeRate() internal view returns (uint256, uint256) { (uint reserve0, uint reserve1) = _getReservesSafe(); uint256 totalSupply = lpToken.totalSupply(); return( reserve0.preciseDiv(totalSupply), reserve1.preciseDiv(totalSupply) ); } // Returns assetOneReserve and assetTwoReserve function _getTotalLPReserves() internal view returns (uint256, uint256) { (uint reserve0, uint reserve1) = _getReservesSafe(); uint256 totalSupply = lpToken.totalSupply(); uint256 lpTokenBalance = rewarder.balanceOf(address(setToken)); return( reserve0.mul(lpTokenBalance).div(totalSupply), reserve1.mul(lpTokenBalance).div(totalSupply) ); } function _updatePositions() internal { uint256 totalSupply = setToken.totalSupply(); uint256 assetOneBalance = assetOne.balanceOf(address(setToken)); uint256 assetTwoBalance = assetTwo.balanceOf(address(setToken)); uint256 lpBalance = rewarder.balanceOf(address(setToken)); // Doesn't check to make sure unit is different, and no check for any LP token on Set setToken.editDefaultPosition(address(assetOne), Position.getDefaultPositionUnit(totalSupply, assetOneBalance)); setToken.editDefaultPosition(address(assetTwo), Position.getDefaultPositionUnit(totalSupply, assetTwoBalance)); setToken.editExternalPosition( address(lpToken), address(this), Position.getDefaultPositionUnit(totalSupply, lpBalance).toInt256(), "" ); } // Code pulled to sort from UniswapV2Library // https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol function _getReservesSafe() internal view returns(uint256, uint256) { address firstAsset = address(assetOne) < address(assetTwo) ? address(assetOne) : address(assetTwo); (uint reserve0, uint reserve1,) = lpToken.getReserves(); return address(assetOne) == firstAsset ? (reserve0, reserve1) : (reserve1, reserve0); } }
Returns desiredOneReserve, desiredTwoReserve, tokenOne and tokenTwo balances
function _getDesiredSingleAssetReserve() internal view returns(uint256, uint256, uint256, uint256) { (uint256 assetOneReserve, uint256 assetTwoReserve) = _getTotalLPReserves(); uint256 balanceAssetOne = assetOne.balanceOf(address(setToken)); uint256 balanceAssetTwo = assetTwo.balanceOf(address(setToken)); uint256 desiredOneReserve = assetOneReserve.add(balanceAssetOne).preciseMul(reservePercentage); uint256 desiredTwoReserve = assetTwoReserve.add(balanceAssetTwo).preciseMul(reservePercentage); return(desiredOneReserve, desiredTwoReserve, balanceAssetOne, balanceAssetTwo); }
1,994,374
[ 1, 1356, 6049, 3335, 607, 6527, 16, 6049, 11710, 607, 6527, 16, 1147, 3335, 471, 1147, 11710, 324, 26488, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 25683, 5281, 6672, 607, 6527, 1435, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 12, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 261, 11890, 5034, 3310, 3335, 607, 6527, 16, 2254, 5034, 3310, 11710, 607, 6527, 13, 273, 389, 588, 5269, 14461, 607, 264, 3324, 5621, 203, 3639, 2254, 5034, 11013, 6672, 3335, 273, 3310, 3335, 18, 12296, 951, 12, 2867, 12, 542, 1345, 10019, 203, 3639, 2254, 5034, 11013, 6672, 11710, 273, 3310, 11710, 18, 12296, 951, 12, 2867, 12, 542, 1345, 10019, 203, 203, 3639, 2254, 5034, 6049, 3335, 607, 6527, 273, 3310, 3335, 607, 6527, 18, 1289, 12, 12296, 6672, 3335, 2934, 4036, 784, 27860, 12, 455, 6527, 16397, 1769, 203, 3639, 2254, 5034, 6049, 11710, 607, 6527, 273, 3310, 11710, 607, 6527, 18, 1289, 12, 12296, 6672, 11710, 2934, 4036, 784, 27860, 12, 455, 6527, 16397, 1769, 203, 203, 3639, 327, 12, 30458, 3335, 607, 6527, 16, 6049, 11710, 607, 6527, 16, 11013, 6672, 3335, 16, 11013, 6672, 11710, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-11-05 */ /* website: bns.finance This project is freshly written to change the way ICO is done. BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNNN SSSSSSSSSSSSSSS DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFIIIIIIIIII B::::::::::::::::B N:::::::N N::::::N SS:::::::::::::::S D::::::::::::DDD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I B::::::BBBBBB:::::B N::::::::N N::::::NS:::::SSSSSS::::::S D:::::::::::::::DD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I BB:::::B B:::::BN:::::::::N N::::::NS:::::S SSSSSSS DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EFF::::::FFFFFFFFF::::FII::::::II B::::B B:::::BN::::::::::N N::::::NS:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F FFFFFF I::::I B::::B B:::::BN:::::::::::N N::::::NS:::::S D:::::D D:::::DE:::::E F:::::F I::::I B::::BBBBBB:::::B N:::::::N::::N N::::::N S::::SSSS D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I B:::::::::::::BB N::::::N N::::N N::::::N SS::::::SSSSS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I B::::BBBBBB:::::B N::::::N N::::N:::::::N SSS::::::::SS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I B::::B B:::::BN::::::N N:::::::::::N SSSSSS::::S D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I B::::B B:::::BN::::::N N::::::::::N S:::::S D:::::D D:::::DE:::::E F:::::F I::::I B::::B B:::::BN::::::N N:::::::::N S:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F I::::I BB:::::BBBBBB::::::BN::::::N N::::::::NSSSSSSS S:::::S DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EFF:::::::FF II::::::II B:::::::::::::::::B N::::::N N:::::::NS::::::SSSSSS:::::S ...... D:::::::::::::::DD E::::::::::::::::::::EF::::::::FF I::::::::I B::::::::::::::::B N::::::N N::::::NS:::::::::::::::SS .::::. D::::::::::::DDD E::::::::::::::::::::EF::::::::FF I::::::::I BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNN SSSSSSSSSSSSSSS ...... DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFF IIIIIIIIII */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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, "SAO"); 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, "SMO"); 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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "IB"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "RR"); } /** * @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, "IBC"); 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), "CNC"); // 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); } } } } /** * @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, "DAB0"); _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, "LF1"); if (returndata.length != 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "LF2"); } } } /** * @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 public _totalSupply; string public _name; string public _symbol; uint8 public _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), "ISA"); require(recipient != address(0), "IRA"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "TIF"); _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), "M0"); _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), "B0"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BIB"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "IA"); require(spender != address(0), "A0"); _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 { } } contract BnsdLaunchPool is Context { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of a raising pool. struct RaisePoolInfo { IERC20 raiseToken; // Address of raising token contract. uint256 maxTokensPerPerson; // Maximum tokens a user can buy. uint256 totalTokensOnSale; // Total tokens available on offer. uint256 startBlock; // When the sale starts uint256 endBlock; // When the sale ends uint256 totalTokensSold; // Total tokens sold to users so far uint256 tokensDeposited; // Total ICO tokens deposited uint256 votes; // Voted by users address owner; // Owner of the pool bool updateLocked; // No pool info can be updated once this is turned ON bool balanceAdded; // Whether ICO tokens are added in correct amount bool paymentMethodAdded; // Supported currencies added or not string poolName; // Human readable string name of the pool } struct AirdropPoolInfo { uint256 totalTokensAvailable; // Total tokens staked so far. IERC20 airdropToken; // Address of staking LP token. bool airdropExists; } // Info of a raising pool. struct UseCasePoolInfo { uint256 tokensAllocated; // Total tokens available for this use uint256 tokensClaimed; // Total tokens claimed address reserveAdd; // Address where tokens will be released for that usecase. bool tokensDeposited; // No pool info can be updated once this is turned ON bool exists; // Whether reserve already exists for a pool string useName; // Human readable string name of the pool uint256[] unlock_perArray; // Release percent for usecase uint256[] unlock_daysArray; // Release days for usecase } struct DistributionInfo { uint256[] percentArray; // Percentage of tokens to be unlocked every phase uint256[] daysArray; // Days from the endDate when tokens starts getting unlocked } // The BNSD TOKEN! address public timeLock; // Dev address. address public devaddr; // Temp dev address while switching address private potentialAdmin; // To store owner diistribution info after sale ends mapping (uint256 => DistributionInfo) private ownerDistInfo; // To store user distribution info after sale ends mapping (uint256 => DistributionInfo) private userDistInfo; // To store tokens on sale and their rates mapping (uint256 => mapping (address => uint256)) public saleRateInfo; // To store invite codes and corresponding token address and pool owners, INVITE CODE => TOKEN => OWNER => bool mapping (uint256 => mapping (address => mapping (address => bool))) private inviteCodeList; // To store user contribution for a sale - POOL => USER => USDT mapping (uint256 => mapping (address => mapping (address => uint256))) public userDepositInfo; // To store total token promised to a user - POOL => USER mapping (uint256 => mapping (address => uint256)) public userTokenAllocation; // To store total token claimed by a user already mapping (uint256 => mapping (address => uint256)) public userTokenClaimed; // To store total token redeemed by users after sale mapping (uint256 => uint256) public totalTokenClaimed; // To store total token raised by a project - POOL => TOKEN => AMT mapping (uint256 => mapping (address => uint256)) public fundsRaisedSoFar; mapping (uint256 => address) private tempAdmin; // To store total token claimed by a project mapping (uint256 => mapping (address => uint256)) public fundsClaimedSoFar; // To store addresses voted for a project - POOL => USER => BOOL mapping (uint256 => mapping (address => bool)) public userVotes; // No of blocks in a day - 6700 uint256 public constant BLOCKS_PER_DAY = 6700; // Changing to 5 for test cases // Info of each pool on blockchain. RaisePoolInfo[] public poolInfo; // Info of reserve pool of any project - POOL => RESERVE_ADD => USECASEINFO mapping (uint256 => mapping (address => UseCasePoolInfo)) public useCaseInfo; // To store total token reserved mapping (uint256 => uint256) public totalTokenReserved; // To store total reserved claimed mapping (uint256 => uint256) public totalReservedTokenClaimed; // To store list of all sales associated with a token mapping (address => uint256[]) public listSaleTokens; // To store list of all currencies allowed for a sale mapping (uint256 => address[]) public listSupportedCurrencies; // To store list of all reserve addresses for a sale mapping (uint256 => address[]) public listReserveAddresses; // To check if staking is enabled on a token mapping (address => bool) public stakingEnabled; // To get staking weight of a token mapping (address => uint256) public stakingWeight; // To store sum of weight of all staking tokens uint256 public totalStakeWeight; // To store list of staking addresses address[] public stakingPools; // To store stats of staked tokens per sale mapping (uint256 => mapping (address => uint256)) public stakedLPTokensInfo; // To store user staked amount for a sale - POOL => USER => LP_TOKEN mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo; // To store reward claimed by a user - POOL => USER => BOOL mapping (uint256 => mapping (address => bool)) public rewardClaimed; // To store airdrop claimed by a user - POOL => USER => BOOL mapping (uint256 => mapping (address => bool)) public airdropClaimed; // To store extra airdrop tokens withdrawn by fund raiser - POOL => BOOL mapping (uint256 => bool) public extraAirdropClaimed; // To store airdrop info for a sale mapping (uint256 => AirdropPoolInfo) public airdropInfo; // To store airdrop tokens balance of a user , TOKEN => USER => BAL mapping (address => mapping (address => uint256)) public airdropBalances; uint256 public fee = 300; // To be divided by 1e4 before using it anywhere => 3.00% uint256 public constant rewardPer = 8000; // To be divided by 1e4 before using it anywhere => 80.00% event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Stake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount); event UnStake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount); event MoveStake(address indexed user, address indexed lptoken, uint256 pid, uint256 indexed pidnew, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event WithdrawAirdrop(address indexed user, address indexed token, uint256 amount); event ClaimAirdrop(address indexed user, address indexed token, uint256 amount); event AirdropDeposit(address indexed user, address indexed token, uint256 indexed pid, uint256 amount); event AirdropExtraWithdraw(address indexed user, address indexed token, uint256 indexed pid, uint256 amount); event Voted(address indexed user, uint256 indexed pid); constructor() public { devaddr = _msgSender(); } modifier onlyAdmin() { require(devaddr == _msgSender(), "ND"); _; } modifier onlyAdminOrTimeLock() { require((devaddr == _msgSender() || timeLock == _msgSender()), "ND"); _; } function setTimeLockAdd(address _add) public onlyAdmin { timeLock = _add; } function poolLength() external view returns (uint256) { return poolInfo.length; } function getListOfSale(address _token) external view returns (uint256[] memory) { return listSaleTokens[_token]; } function getUserDistPercent(uint256 _pid) external view returns (uint256[] memory) { return userDistInfo[_pid].percentArray; } function getUserDistDays(uint256 _pid) external view returns (uint256[] memory) { return userDistInfo[_pid].daysArray; } function getReserveUnlockPercent(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) { return useCaseInfo[_pid][_reserveAdd].unlock_perArray; } function getReserveUnlockDays(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) { return useCaseInfo[_pid][_reserveAdd].unlock_daysArray; } function getUserDistBlocks(uint256 _pid) external view returns (uint256[] memory) { uint256[] memory daysArray = userDistInfo[_pid].daysArray; uint256 endPool = poolInfo[_pid].endBlock; for(uint256 i=0; i<daysArray.length; i++){ daysArray[i] = (daysArray[i].mul(BLOCKS_PER_DAY)).add(endPool); } return daysArray; } function getOwnerDistPercent(uint256 _pid) external view returns (uint256[] memory) { return ownerDistInfo[_pid].percentArray; } function getOwnerDistDays(uint256 _pid) external view returns (uint256[] memory) { return ownerDistInfo[_pid].daysArray; } // Add a new token sale to the pool. Can only be called by the person having the invite code. function addNewPool(uint256 totalTokens, uint256 maxPerPerson, uint256 startBlock, uint256 endBlock, string memory namePool, IERC20 tokenAddress, uint256 _inviteCode) external returns (uint256) { require(endBlock > startBlock, "ESC"); // END START COMPARISON FAILED require(startBlock > block.number, "TLS"); // TIME LIMIT START SALE require(maxPerPerson !=0 && totalTokens!=0, "IIP"); // INVALID INDIVIDUAL PER PERSON require(inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()]==true,"IIC"); // INVALID INVITE CODE poolInfo.push(RaisePoolInfo({ raiseToken: tokenAddress, maxTokensPerPerson: maxPerPerson, totalTokensOnSale: totalTokens, startBlock: startBlock, endBlock: endBlock, poolName: namePool, updateLocked: false, owner: _msgSender(), totalTokensSold: 0, balanceAdded: false, tokensDeposited: 0, paymentMethodAdded: false, votes: 0 })); uint256 poolId = (poolInfo.length - 1); listSaleTokens[address(tokenAddress)].push(poolId); // This makes the invite code claimed inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()] = false; return poolId; } function _checkSumArray(uint256[] memory _percentArray) internal pure returns (bool) { uint256 _sum; for (uint256 i = 0; i < _percentArray.length; i++) { _sum = _sum.add(_percentArray[i]); } return (_sum==10000); } function _checkValidDaysArray(uint256[] memory _daysArray) internal pure returns (bool) { uint256 _lastDay = _daysArray[0]; for (uint256 i = 1; i < _daysArray.length; i++) { if(_lastDay < _daysArray[i]){ _lastDay = _daysArray[i]; } else { return false; } } return true; } function _checkUpdateAllowed(uint256 _pid) internal view{ RaisePoolInfo storage pool = poolInfo[_pid]; require(pool.updateLocked == false, "CT2"); // CRITICAL TERMINATION 2 require(pool.owner==_msgSender(), "OAU"); // OWNER AUTHORIZATION FAILED require(pool.startBlock > block.number, "CT"); // CRITICAL TERMINATION } // Add rule for funds locking after sale function updateUserDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external { require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH _checkUpdateAllowed(_pid); require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING userDistInfo[_pid] = DistributionInfo({ percentArray: _percentArray, daysArray: _daysArray }); } // Add rule for funds unlocking of the fund raiser after sale function updateOwnerDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external { require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH _checkUpdateAllowed(_pid); require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING ownerDistInfo[_pid] = DistributionInfo({ percentArray: _percentArray, daysArray: _daysArray }); } // Lock sale detail changes in future function lockPool(uint256 _pid) external { require(poolInfo[_pid].paymentMethodAdded==true, "CP"); // CHECK PAYMENT METHOD FAILED _checkUpdateAllowed(_pid); poolInfo[_pid].updateLocked = true; } // Add supported currencies and their rate w.r.t token on sale // rateToken = price of one satoshi of the token in terms of token to be raised * 1e18 // 1 BNSD = 0.00021 ETH => 1e18 BNSD Satoshi = 0.00021 * 1e18 ETH satoshi => 1 BNSD Satoshi = 0.00021 ETH satoshi => rateToken = 0.00021 * 1e18 = 21 * 1e13 // rateToken for BNSD/ETH pair = 21 * 1e13; function addSupportedCurrencies(uint256 _pid, address _tokenRaise, uint256 rateToken) external { _checkUpdateAllowed(_pid); require(rateToken!=0, "IR"); // INVALID RATE require(_tokenRaise!=address(poolInfo[_pid].raiseToken), "IT"); // INVALIID PURCHASE TOKEN if(address(this).balance == 0){ //inject PRESENT ETHER listSupportedCurrencies[_pid].push(_tokenRaise); } saleRateInfo[_pid][_tokenRaise] = rateToken; poolInfo[_pid].paymentMethodAdded = true; } function getSupportedCurrencies(uint256 _pid) external view returns (address[] memory) { return listSupportedCurrencies[_pid]; } function _checkUpdateReserveAllowed(uint256 _pid, address _resAdd) internal view returns (bool) { UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; return (poolU.exists == false || poolU.tokensDeposited == false); // if(poolU.exists == false || poolU.tokensDeposited == false){ // return true; // } // return false; } function addReservePool(uint256 _pid, address _reserveAdd, string memory _nameReserve, uint256 _totalTokens, uint256[] memory _perArray, uint256[] memory _daysArray) external { _checkUpdateAllowed(_pid); require(_checkUpdateReserveAllowed(_pid, _reserveAdd) == true, "UB"); // UPDATE RESERVE FAILED require(_checkSumArray(_perArray), "SE"); // SUM OF PERCENT INVALID require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING require(_perArray.length==_daysArray.length, "IAL"); // INVALID ARRAY LENGTH if(useCaseInfo[_pid][_reserveAdd].exists == false){ listReserveAddresses[_pid].push(_reserveAdd); } useCaseInfo[_pid][_reserveAdd] = UseCasePoolInfo({ reserveAdd: _reserveAdd, useName: _nameReserve, tokensAllocated: _totalTokens, unlock_perArray: _perArray, unlock_daysArray: _daysArray, tokensDeposited: false, tokensClaimed: 0, exists: true }); } function getReserveAddresses(uint256 _pid) external view returns (address[] memory) { return listReserveAddresses[_pid]; } function tokensPurchaseAmt(uint256 _pid, address _tokenAdd, uint256 amt) public view returns (uint256) { uint256 rateToken = saleRateInfo[_pid][_tokenAdd]; require(rateToken!=0, "NAT"); // NOT AVAILABLE TOKEN return (amt.mul(1e18)).div(rateToken); } // Check if user can deposit specfic amount of funds to the pool function _checkDepositAllowed(uint256 _pid, address _tokenAdd, uint256 _amt) internal view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; uint256 userBought = userTokenAllocation[_pid][_msgSender()]; uint256 purchasePossible = tokensPurchaseAmt(_pid, _tokenAdd, _amt); require(pool.balanceAdded == true, "NA"); // NOT AVAILABLE require(pool.startBlock <= block.number, "NT1"); // NOT AVAILABLE TIME 1 require(pool.endBlock >= block.number, "NT2"); // NOT AVAILABLE TIME 2 require(pool.totalTokensSold.add(purchasePossible) <= pool.totalTokensOnSale, "PLE"); // POOL LIMIT EXCEEDED require(userBought.add(purchasePossible) <= pool.maxTokensPerPerson, "ILE"); // INDIVIDUAL LIMIT EXCEEDED return purchasePossible; } // Check max a user can deposit right now function getMaxDepositAllowed(uint256 _pid, address _tokenAdd, address _user) external view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; uint256 maxBuyPossible = (pool.maxTokensPerPerson).sub(userTokenAllocation[_pid][_user]); uint256 maxBuyPossiblePoolLimit = (pool.totalTokensOnSale).sub(pool.totalTokensSold); if(maxBuyPossiblePoolLimit < maxBuyPossible){ maxBuyPossible = maxBuyPossiblePoolLimit; } if(block.number >= pool.startBlock && block.number <= pool.endBlock && pool.balanceAdded == true){ uint256 rateToken = saleRateInfo[_pid][_tokenAdd]; return (maxBuyPossible.mul(rateToken).div(1e18)); } else { return 0; } } // Check if deposit is enabled for a pool function checkDepositEnabled(uint256 _pid) external view returns (bool){ RaisePoolInfo storage pool = poolInfo[_pid]; if(pool.balanceAdded == true && pool.startBlock <= block.number && pool.endBlock >= block.number && pool.totalTokensSold <= pool.totalTokensOnSale && pool.paymentMethodAdded==true){ return true; } else { return false; } } // Deposit ICO tokens to start a pool for ICO. function depositICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; address msgSender = _msgSender(); require(_tokenAdd == pool.raiseToken, "NOT"); // NOT VALID TOKEN require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER require(block.number < pool.endBlock, "NT"); // No point adding tokens after sale has ended - Possible deadlock case _tokenAdd.safeTransferFrom(msgSender, address(this), _amount); pool.tokensDeposited = (pool.tokensDeposited).add(_amount); if(pool.tokensDeposited >= pool.totalTokensOnSale){ pool.balanceAdded = true; } emit Deposit(msgSender, _pid, _amount); } // Deposit Airdrop tokens anytime before end of the sale. function depositAirdropTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number < pool.endBlock, "NT"); // NOT VALID TIME AirdropPoolInfo storage airdrop = airdropInfo[_pid]; require((_tokenAdd == airdrop.airdropToken || airdrop.airdropExists==false), "NOT"); // NOT VALID TOKEN require(_msgSender() == pool.owner || _msgSender() == devaddr , "NAU"); // NOT AUTHORISED USER _tokenAdd.safeTransferFrom(_msgSender(), address(this), _amount); airdrop.totalTokensAvailable = (airdrop.totalTokensAvailable).add(_amount); if(!airdrop.airdropExists){ airdrop.airdropToken = _tokenAdd; airdrop.airdropExists = true; } emit AirdropDeposit(_msgSender(), address(_tokenAdd), _pid, _amount); } // Withdraw extra airdrop tokens - Possible only if no one added liquidity to one of the pools function withdrawExtraAirdropTokens(uint256 _pid) external { require(extraAirdropClaimed[_pid]==false, "NA"); // NOT AVAILABLE RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number > pool.endBlock, "NSE"); // SALE NOT ENDED address msgSender = _msgSender(); require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER uint256 extraTokens = calculateExtraAirdropTokens(_pid); require(extraTokens!=0, "NAT"); // NOT AVAILABLE TOKEN extraAirdropClaimed[_pid] = true; airdropInfo[_pid].airdropToken.safeTransfer(msgSender, extraTokens); emit AirdropExtraWithdraw(msg.sender, address(airdropInfo[_pid].airdropToken), _pid, extraTokens); } function calculateExtraAirdropTokens(uint256 _pid) public view returns (uint256){ if(extraAirdropClaimed[_pid] == true) return 0; uint256 _totalTokens; for (uint256 i=0; i<stakingPools.length; i++){ uint256 stake = stakedLPTokensInfo[_pid][stakingPools[i]]; if(address(this).balance == 0){ //inject PRESENT ETHER _totalTokens = _totalTokens.add(((stakingWeight[stakingPools[i]]).mul(airdropInfo[_pid].totalTokensAvailable)).div(totalStakeWeight)); } } return _totalTokens; } // Deposit LP tokens for a sale. function stakeLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external { require(stakingEnabled[address(_lpAdd)]==true, "NST"); // NOT STAKING TOKEN RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number < pool.startBlock, "NT"); // NOT VALID TIME address msgSender = _msgSender(); _lpAdd.safeTransferFrom(msgSender, address(this), _amount); stakedLPTokensInfo[_pid][address(_lpAdd)] = (stakedLPTokensInfo[_pid][address(_lpAdd)]).add(_amount); userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).add(_amount); emit Stake(msg.sender, address(_lpAdd), _pid, _amount); } // Withdraw LP tokens from a sale after it's over => Automatically claims rewards and airdrops also function withdrawLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external { require(stakingEnabled[address(_lpAdd)]==true, "NAT"); // NOT AUTHORISED TOKEN RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number > pool.endBlock, "SE"); // SALE NOT ENDED address msgSender = _msgSender(); claimRewardAndAirdrop(_pid); userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).sub(_amount); _lpAdd.safeTransfer(msgSender, _amount); emit UnStake(msg.sender, address(_lpAdd), _pid, _amount); } // Withdraw airdrop tokens accumulated over one or more than one sale. function withdrawAirdropTokens(IERC20 _token, uint256 _amount) external { address msgSender = _msgSender(); airdropBalances[address(_token)][msgSender] = (airdropBalances[address(_token)][msgSender]).sub(_amount); _token.safeTransfer(msgSender, _amount); emit WithdrawAirdrop(msgSender, address(_token), _amount); } // Move LP tokens from one sale to another directly => Automatically claims rewards and airdrops also function moveLPTokens(uint256 _pid, uint256 _newpid, uint256 _amount, address _lpAdd) external { require(stakingEnabled[_lpAdd]==true, "NAT1"); // NOT AUTHORISED TOKEN 1 RaisePoolInfo storage poolOld = poolInfo[_pid]; RaisePoolInfo storage poolNew = poolInfo[_newpid]; require(block.number > poolOld.endBlock, "NUA"); // OLD SALE NOT ENDED require(block.number < poolNew.startBlock, "NSA"); // SALE START CHECK FAILED address msgSender = _msgSender(); claimRewardAndAirdrop(_pid); userStakeInfo[_pid][msgSender][_lpAdd] = (userStakeInfo[_pid][msgSender][_lpAdd]).sub(_amount); userStakeInfo[_newpid][msgSender][_lpAdd] = (userStakeInfo[_newpid][msgSender][_lpAdd]).add(_amount); emit MoveStake(msg.sender, _lpAdd, _pid, _newpid, _amount); } function claimRewardAndAirdrop(uint256 _pid) public { RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number > pool.endBlock, "SE"); // SUM INVALID _claimReward(_pid, _msgSender()); _claimAirdrop(_pid, _msgSender()); } function _claimReward(uint256 _pid, address _user) internal { if (rewardClaimed[_pid][_user]==false){ rewardClaimed[_pid][_user] = true; for (uint256 i=0; i<stakingPools.length; i++){ for(uint256 j=0; j<listSupportedCurrencies[_pid].length; j++){ uint256 _tokenAmt = getReward(_pid, _user, stakingPools[i], listSupportedCurrencies[_pid][j]); _creditAirdrop(_user, listSupportedCurrencies[_pid][j], _tokenAmt); } } } } function _claimAirdrop(uint256 _pid, address _user) internal { if (airdropClaimed[_pid][_user]==false){ airdropClaimed[_pid][_user] = true; address _airdropToken = address(airdropInfo[_pid].airdropToken); uint256 _tokenAmt = 0; for (uint256 i=0; i<stakingPools.length; i++){ _tokenAmt = _tokenAmt.add(getAirdrop(_pid, _user, stakingPools[i])); } if(_tokenAmt !=0){ _creditAirdrop(_user, _airdropToken, _tokenAmt); } } } function _creditAirdrop(address _user, address _token, uint256 _amt) internal { airdropBalances[_token][_user] = (airdropBalances[_token][_user]).add(_amt); emit ClaimAirdrop(_user, _token, _amt); } function getReward(uint256 _pid, address _user, address _lpAdd, address _token) public view returns (uint256) { uint256 stake = stakedLPTokensInfo[_pid][_lpAdd]; if(address(this).balance==0) return 0; //inject PRESENT ETHER uint256 _multipliedData = (userStakeInfo[_pid][_user][_lpAdd]).mul(fundsRaisedSoFar[_pid][_token]); _multipliedData = (_multipliedData).mul(rewardPer).mul(fee).mul(stakingWeight[_lpAdd]); return (((_multipliedData).div(stake)).div(1e8)).div(totalStakeWeight); } function getAirdrop(uint256 _pid, address _user, address _lpAdd) public view returns (uint256) { uint256 _userStaked = userStakeInfo[_pid][_user][_lpAdd]; uint256 _totalStaked = stakedLPTokensInfo[_pid][_lpAdd]; if(address(this).balance==0) return 0; //inject PRESENT ETHER return ((((_userStaked).mul(airdropInfo[_pid].totalTokensAvailable).mul(stakingWeight[_lpAdd])).div(_totalStaked))).div(totalStakeWeight); } // Deposit ICO tokens for a use case as reserve. function depositReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd, address _resAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; address msgSender = _msgSender(); require(_tokenAdd == pool.raiseToken, "NOT"); // NOT AUTHORISED TOKEN require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER require(poolU.tokensDeposited == false, "DR"); // TOKENS NOT DEPOSITED require(poolU.tokensAllocated == _amount && _amount!=0, "NA"); // NOT AVAILABLE require(block.number < pool.endBlock, "CRN"); // CANNOT_RESERVE_NOW to avoid deadlocks _tokenAdd.safeTransferFrom(msgSender, address(this), _amount); totalTokenReserved[_pid] = (totalTokenReserved[_pid]).add(_amount); poolU.tokensDeposited = true; emit Deposit(msg.sender, _pid, _amount); } // Withdraw extra unsold ICO tokens or extra deposited tokens. function withdrawExtraICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; address msgSender = _msgSender(); require(_tokenAdd == pool.raiseToken, "NT"); // NOT AUTHORISED TOKEN require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER require(block.number > pool.endBlock, "NA"); // NOT AVAILABLE TIME uint256 _amtAvail = pool.tokensDeposited.sub(pool.totalTokensSold); require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE TOKEN pool.tokensDeposited = (pool.tokensDeposited).sub(_amount); _tokenAdd.safeTransfer(msgSender, _amount); emit Withdraw(msgSender, _pid, _amount); } // Fetch extra ICO tokens available. function fetchExtraICOTokens(uint256 _pid) external view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; return pool.tokensDeposited.sub(pool.totalTokensSold); } // Deposit tokens to a pool for ICO. function deposit(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { address msgSender = _msgSender(); uint256 _buyThisStep = _checkDepositAllowed(_pid, address(_tokenAdd), _amount); // require(_buyThisStep >= _amount, "CDE"); _tokenAdd.safeTransferFrom(msgSender, address(this), _amount); userDepositInfo[_pid][msgSender][address(_tokenAdd)] = userDepositInfo[_pid][msgSender][address(_tokenAdd)].add(_amount); userTokenAllocation[_pid][msgSender] = userTokenAllocation[_pid][msgSender].add(_buyThisStep); poolInfo[_pid].totalTokensSold = poolInfo[_pid].totalTokensSold.add(_buyThisStep); fundsRaisedSoFar[_pid][address(_tokenAdd)] = fundsRaisedSoFar[_pid][address(_tokenAdd)].add(_amount); emit Deposit(msg.sender, _pid, _amount); } // Vote your favourite ICO project. function voteProject(uint256 _pid) external { address msgSender = _msgSender(); require(userVotes[_pid][msgSender]==false,"AVO"); // ALREADY VOTED require(poolInfo[_pid].endBlock >= block.number,"CVO"); // CANNOT VOTE NOW userVotes[_pid][msgSender] = true; poolInfo[_pid].votes = (poolInfo[_pid].votes).add(1); emit Voted(msgSender, _pid); } function _calculatePerAvailable(uint256[] memory _daysArray, uint256[] memory _percentArray, uint256 blockEnd) internal view returns (uint256) { uint256 _defaultPer = 10000; uint256 _perNow; if(address(this).balance==0){ //inject PRESENT ETHER return _defaultPer; } uint256 daysDone = ((block.number).sub(blockEnd)).div(BLOCKS_PER_DAY); for (uint256 i = 0; i < _daysArray.length; i++) { if(_daysArray[i] <= daysDone){ _perNow = _perNow.add(_percentArray[i]); } else { break; } } return _perNow; } function _getPercentAvailable(uint256 _pid, uint256 blockEnd) internal view returns (uint256){ DistributionInfo storage distInfo = userDistInfo[_pid]; uint256[] storage _percentArray = distInfo.percentArray; uint256[] storage _daysArray = distInfo.daysArray; return _calculatePerAvailable(_daysArray, _percentArray, blockEnd); } // Check amount of ICO tokens withdrawable by user till now - public function amountAvailToWithdrawUser(uint256 _pid, address _user) public view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; if(pool.endBlock < block.number){ uint256 percentAvail = _getPercentAvailable(_pid, pool.endBlock); return ((percentAvail).mul(userTokenAllocation[_pid][_user]).div(10000)).sub(userTokenClaimed[_pid][_user]); } else { return 0; } } // Withdraw ICO tokens after sale is over based on distribution rules. function withdrawUser(uint256 _pid, uint256 _amount) external { RaisePoolInfo storage pool = poolInfo[_pid]; address msgSender = _msgSender(); uint256 _amtAvail = amountAvailToWithdrawUser(_pid, msgSender); require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN userTokenClaimed[_pid][msgSender] = userTokenClaimed[_pid][msgSender].add(_amount); totalTokenClaimed[_pid] = totalTokenClaimed[_pid].add(_amount); pool.raiseToken.safeTransfer(msgSender, _amount); emit Withdraw(msgSender, _pid, _amount); } function _getPercentAvailableFundRaiser(uint256 _pid, uint256 blockEnd) internal view returns (uint256){ DistributionInfo storage distInfo = ownerDistInfo[_pid]; uint256[] storage _percentArray = distInfo.percentArray; uint256[] storage _daysArray = distInfo.daysArray; return _calculatePerAvailable(_daysArray, _percentArray, blockEnd); } // Check amount of ICO tokens withdrawable by user till now function amountAvailToWithdrawFundRaiser(uint256 _pid, IERC20 _tokenAdd) public view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; if(pool.endBlock < block.number){ uint256 percentAvail = _getPercentAvailableFundRaiser(_pid, pool.endBlock); return (((percentAvail).mul(fundsRaisedSoFar[_pid][address(_tokenAdd)]).div(10000))).sub(fundsClaimedSoFar[_pid][address(_tokenAdd)]); } else { return 0; } } function _getPercentAvailableReserve(uint256 _pid, uint256 blockEnd, address _resAdd) internal view returns (uint256){ UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; uint256[] storage _percentArray = poolU.unlock_perArray; uint256[] storage _daysArray = poolU.unlock_daysArray; return _calculatePerAvailable(_daysArray, _percentArray, blockEnd); } // Check amount of ICO tokens withdrawable by reserve user till now function amountAvailToWithdrawReserve(uint256 _pid, address _resAdd) public view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; if(pool.endBlock < block.number){ uint256 percentAvail = _getPercentAvailableReserve(_pid, pool.endBlock, _resAdd); return ((percentAvail).mul(poolU.tokensAllocated).div(10000)).sub(poolU.tokensClaimed); } else { return 0; } } // Withdraw ICO tokens for various use cases as per the schedule promised on provided address. function withdrawReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { UseCasePoolInfo storage poolU = useCaseInfo[_pid][_msgSender()]; require(poolU.reserveAdd == _msgSender(), "NAUTH"); // NOT AUTHORISED USER require(_tokenAdd == poolInfo[_pid].raiseToken, "NT"); // NOT AUTHORISED TOKEN uint256 _amtAvail = amountAvailToWithdrawReserve(_pid, _msgSender()); require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE USER poolU.tokensClaimed = poolU.tokensClaimed.add(_amount); totalTokenReserved[_pid] = totalTokenReserved[_pid].sub(_amount); totalReservedTokenClaimed[_pid] = totalReservedTokenClaimed[_pid].add(_amount); _tokenAdd.safeTransfer(_msgSender(), _amount); emit Withdraw(_msgSender(), _pid, _amount); } // Withdraw raised funds after sale is over as per the schedule promised function withdrawFundRaiser(uint256 _pid, uint256 _amount, IERC20 _tokenAddress) external { RaisePoolInfo storage pool = poolInfo[_pid]; require(pool.owner == _msgSender(), "NAUTH"); // NOT AUTHORISED USER uint256 _amtAvail = amountAvailToWithdrawFundRaiser(_pid, _tokenAddress); require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN uint256 _fee = ((_amount).mul(fee)).div(1e4); uint256 _actualTransfer = _amtAvail.sub(_fee); uint256 _feeDev = (_fee).mul(10000 - rewardPer).div(1e4); // Remaining tokens for reward mining fundsClaimedSoFar[_pid][address(_tokenAddress)] = fundsClaimedSoFar[_pid][address(_tokenAddress)].add(_amount); _tokenAddress.safeTransfer(_msgSender(), _actualTransfer); _tokenAddress.safeTransfer(devaddr, _feeDev); emit Withdraw(_msgSender(), _pid, _actualTransfer); emit Withdraw(devaddr, _pid, _feeDev); } // Update dev address by initiating with the previous dev. function changeDev(address _newowner) external onlyAdmin { potentialAdmin = _newowner; } function becomeDev() external { require(potentialAdmin == msg.sender, "NA"); // NOT ALLOWED devaddr = msg.sender; } // Update temp pool owner address by initiating with the previous pool owner. function changePoolOwner(uint256 _pid, address _newowner) external { require(_msgSender()==poolInfo[_pid].owner, "OA"); // NOT AUTHORISED USER tempAdmin[_pid] = _newowner; } // Claim pool ownership with new address function becomePoolOwner(uint256 _pid) external { if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender(); } // Update fee, can never be more than 3%. function changeFee(uint256 _fee) external onlyAdmin{ require(_fee <= 300, "MAX3"); // MAX FEE POSSIBLE fee = _fee; } // To generate a new invite code function generateNewCode(address _token, address _poolOwner) external onlyAdminOrTimeLock returns (uint256) { uint256 inviteCode = block.number; inviteCodeList[inviteCode][_token][_poolOwner] = true; return inviteCode; } // To invalidate an invite code function invalidateOldCode(uint256 _inviteCode, address _token, address _poolOwner) external onlyAdmin { inviteCodeList[_inviteCode][_token][_poolOwner] = false; } // To add or update a staking pool with weight function addStakingPool(address _token, uint256 _weight) external onlyAdmin { if(stakingEnabled[_token]==false){ stakingPools.push(_token); stakingEnabled[_token] = true; } totalStakeWeight = totalStakeWeight.sub(stakingWeight[_token]).add(_weight); stakingWeight[_token] = _weight; } }
Check amount of ICO tokens withdrawable by reserve user till now
function amountAvailToWithdrawReserve(uint256 _pid, address _resAdd) public view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; if(pool.endBlock < block.number){ uint256 percentAvail = _getPercentAvailableReserve(_pid, pool.endBlock, _resAdd); return ((percentAvail).mul(poolU.tokensAllocated).div(10000)).sub(poolU.tokensClaimed); } else { return 0; } }
1,045,338
[ 1, 1564, 3844, 434, 467, 3865, 2430, 598, 9446, 429, 635, 20501, 729, 21364, 2037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3844, 3769, 671, 774, 1190, 9446, 607, 6527, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 455, 986, 13, 1071, 1476, 1135, 261, 11890, 5034, 15329, 203, 3639, 20539, 2864, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 2672, 2449, 2864, 966, 2502, 2845, 57, 273, 999, 2449, 966, 63, 67, 6610, 6362, 67, 455, 986, 15533, 203, 3639, 309, 12, 6011, 18, 409, 1768, 411, 1203, 18, 2696, 15329, 203, 5411, 2254, 5034, 5551, 3769, 671, 273, 389, 588, 8410, 5268, 607, 6527, 24899, 6610, 16, 2845, 18, 409, 1768, 16, 389, 455, 986, 1769, 203, 5411, 327, 14015, 8849, 3769, 671, 2934, 16411, 12, 6011, 57, 18, 7860, 29392, 2934, 2892, 12, 23899, 13, 2934, 1717, 12, 6011, 57, 18, 7860, 9762, 329, 1769, 203, 3639, 289, 203, 3639, 469, 288, 203, 5411, 327, 374, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // interfaces import {IERC725Y} from "@erc725/smart-contracts/contracts/interfaces/IERC725Y.sol"; // libraries import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol"; import {LSP2Utils} from "../LSP2ERC725YJSONSchema/LSP2Utils.sol"; import {LSP6Utils} from "../LSP6KeyManager/LSP6Utils.sol"; import {UtilsLib} from "../Utils/UtilsLib.sol"; // constants import {_TYPEID_LSP7_TOKENSSENDER} from "../LSP7DigitalAsset/LSP7Constants.sol"; library LSP5Utils { /** * @dev Generating the data keys/values to be set on the account after receiving assets/vaults * * @param account The account where the Keys should be added * @param arrayLengthKey The arrayLengthKey containing the number of the received assets/vaults * @param mapKey The mapKey containing the interfaceID and the index of the asset in the `element in arrayKey` * @param caller The address of the asset/vault received * @param interfaceID The interfaceID of the asset/vault received */ function addMapAndArrayKey( IERC725Y account, bytes32 arrayLengthKey, bytes32 mapKey, address caller, bytes4 interfaceID ) internal view returns (bytes32[] memory keys, bytes[] memory values) { /** * We will be setting 3 keys: * - Keys[0]: The arrayLengthKey containing the number of the received assets/vaults * - Keys[1]: The element in arrayKey containing the address of each received asset/vault for a specific index * - Keys[2]: The mapKey containing the interfaceID and the index of the asset in the `element in arrayKey` */ keys = new bytes32[](3); values = new bytes[](3); bytes memory encodedArrayLength = account.getData(arrayLengthKey); // If it's the first asset to receive if (encodedArrayLength.length == 0) { keys[0] = arrayLengthKey; values[0] = UtilsLib.uint256ToBytes(1); keys[1] = LSP2Utils.generateArrayElementKeyAtIndex(arrayLengthKey, 0); values[1] = UtilsLib.addressToBytes(caller); keys[2] = mapKey; values[2] = bytes.concat(interfaceID, bytes8(0)); // If the storage is already initiated } else if (encodedArrayLength.length == 32) { uint256 arrayLength = abi.decode(encodedArrayLength, (uint256)); uint256 newArrayLength = arrayLength + 1; keys[0] = arrayLengthKey; values[0] = UtilsLib.uint256ToBytes(newArrayLength); keys[1] = LSP2Utils.generateArrayElementKeyAtIndex(arrayLengthKey, newArrayLength - 1); values[1] = UtilsLib.addressToBytes(caller); keys[2] = mapKey; values[2] = bytes.concat(interfaceID, bytes8(uint64(arrayLength))); } else { revert("Invalid length of the LSP5ReceivedAssets[] Key"); } } /** * @dev Generating the data keys/values to be removed/changed on the account after sending assets/vaults * * @param account The account where the Keys should be added * @param arrayLengthKey The arrayLengthKey containing the number of the received assets/vaults * @param mapKeyPrefix The mapKey prefix relative to LSP5ReceivedAssetsMap or LSP10VaultsMap Keys * @param mapKeyToRemove The mapKey of the asset sent * @param mapValue The mapValue of the asset/vault sent */ function removeMapAndArrayKey( IERC725Y account, bytes32 arrayLengthKey, bytes12 mapKeyPrefix, bytes32 mapKeyToRemove, bytes memory mapValue ) internal view returns (bytes32[] memory keys, bytes[] memory values) { // Updating the number of the received assets/vaults bytes memory encodedArrayLength = account.getData(arrayLengthKey); uint256 arrayLength = abi.decode(encodedArrayLength, (uint256)); uint256 newLength = arrayLength - 1; uint64 index = extractIndexFromMap(mapValue); bytes32 arrayElementKeyToRemove = LSP2Utils.generateArrayElementKeyAtIndex( arrayLengthKey, index ); if (index == (arrayLength - 1)) { /** * We will be updating/removing 3 keys: * - Keys[0]: [Update] The arrayLengthKey to contain the new number of the received assets/vaults * - Keys[1]: [Remove] The element in arrayKey (Remove the address of the asset sent) * - Keys[2]: [Remove] The mapKey (Remove the interfaceId and the index of the asset sent) */ keys = new bytes32[](3); values = new bytes[](3); keys[0] = arrayLengthKey; values[0] = UtilsLib.uint256ToBytes(newLength); keys[1] = mapKeyToRemove; values[1] = ""; keys[2] = arrayElementKeyToRemove; values[2] = ""; // Swapping last element in ArrayKey with the elemnt in ArrayKey to remove || {Swap and pop} method; // check https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol#L80 } else { /** * We will be updating/removing 5 keys: * - Keys[0]: [Update] The arrayLengthKey to contain the new number of the received assets/vaults * - Keys[1]: [Remove] The mapKey of the asset to remove (Remove the interfaceId and the index of the asset sent) * - Keys[2]: [Update] The element in arrayKey to remove (Swap with the address of the last element in Array) * - Keys[3]: [Remove] The last element in arrayKey (Remove (pop) the address of the last element as it's already swapped) * - Keys[4]: [Update] The mapKey of the last element in array (Update the new index and the interfaceID) */ keys = new bytes32[](5); values = new bytes[](5); keys[0] = arrayLengthKey; values[0] = UtilsLib.uint256ToBytes(newLength); keys[1] = mapKeyToRemove; values[1] = ""; // Generate all data Keys/values of the last element in Array to swap // with data Keys/values of the asset to remove bytes32 lastArrayElementKey = LSP2Utils.generateArrayElementKeyAtIndex( arrayLengthKey, newLength ); bytes memory lastArrayElementValue = account.getData(lastArrayElementKey); bytes32 lastArrayElementMapKey = LSP2Utils.generateMappingKey( mapKeyPrefix, bytes20(lastArrayElementValue) ); bytes memory lastArrayElementMapValue = account.getData(lastArrayElementMapKey); bytes memory interfaceID = BytesLib.slice(lastArrayElementMapValue, 0, 4); keys[2] = arrayElementKeyToRemove; values[2] = lastArrayElementValue; keys[3] = lastArrayElementKey; values[3] = ""; keys[4] = lastArrayElementMapKey; values[4] = bytes.concat(interfaceID, bytes8(index)); } } function addMapAndArrayKeyViaKeyManager( IERC725Y account, bytes32 arrayLengthKey, bytes32 mapKey, address caller, bytes4 interfaceID, address keyManager ) internal returns (bytes memory result) { (bytes32[] memory keys, bytes[] memory values) = addMapAndArrayKey( account, arrayLengthKey, mapKey, caller, interfaceID ); result = LSP6Utils.setDataViaKeyManager(keyManager, keys, values); } function removeMapAndArrayKeyViaKeyManager( IERC725Y account, bytes32 arrayLengthKey, bytes12 mapKeyPrefix, bytes32 mapKeyToRemove, bytes memory mapValue, address keyManager ) internal returns (bytes memory result) { (bytes32[] memory keys, bytes[] memory values) = removeMapAndArrayKey( account, arrayLengthKey, mapKeyPrefix, mapKeyToRemove, mapValue ); result = LSP6Utils.setDataViaKeyManager(keyManager, keys, values); } function extractIndexFromMap(bytes memory mapValue) internal pure returns (uint64) { bytes memory val = BytesLib.slice(mapValue, 4, 8); return BytesLib.toUint64(val, 0); } }
* @dev Generating the data keys/values to be set on the account after receiving assets/vaults @param account The account where the Keys should be added @param arrayLengthKey The arrayLengthKey containing the number of the received assets/vaults @param mapKey The mapKey containing the interfaceID and the index of the asset in the `element in arrayKey` @param caller The address of the asset/vault received @param interfaceID The interfaceID of the asset/vault received/ If it's the first asset to receive If the storage is already initiated
) internal view returns (bytes32[] memory keys, bytes[] memory values) { keys = new bytes32[](3); values = new bytes[](3); bytes memory encodedArrayLength = account.getData(arrayLengthKey); if (encodedArrayLength.length == 0) { keys[0] = arrayLengthKey; values[0] = UtilsLib.uint256ToBytes(1); keys[1] = LSP2Utils.generateArrayElementKeyAtIndex(arrayLengthKey, 0); values[1] = UtilsLib.addressToBytes(caller); keys[2] = mapKey; values[2] = bytes.concat(interfaceID, bytes8(0)); uint256 arrayLength = abi.decode(encodedArrayLength, (uint256)); uint256 newArrayLength = arrayLength + 1; keys[0] = arrayLengthKey; values[0] = UtilsLib.uint256ToBytes(newArrayLength); keys[1] = LSP2Utils.generateArrayElementKeyAtIndex(arrayLengthKey, newArrayLength - 1); values[1] = UtilsLib.addressToBytes(caller); keys[2] = mapKey; values[2] = bytes.concat(interfaceID, bytes8(uint64(arrayLength))); revert("Invalid length of the LSP5ReceivedAssets[] Key"); } }
12,578,088
[ 1, 21755, 326, 501, 1311, 19, 2372, 358, 506, 444, 603, 326, 2236, 1839, 15847, 7176, 19, 26983, 87, 225, 2236, 1021, 2236, 1625, 326, 11432, 1410, 506, 3096, 225, 526, 1782, 653, 1021, 526, 1782, 653, 4191, 326, 1300, 434, 326, 5079, 7176, 19, 26983, 87, 225, 852, 653, 1021, 852, 653, 4191, 326, 1560, 734, 471, 326, 770, 434, 326, 3310, 316, 326, 1375, 2956, 316, 526, 653, 68, 225, 4894, 1021, 1758, 434, 326, 3310, 19, 26983, 5079, 225, 1560, 734, 1021, 1560, 734, 434, 326, 3310, 19, 26983, 5079, 19, 971, 518, 1807, 326, 1122, 3310, 358, 6798, 971, 326, 2502, 353, 1818, 27183, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 1476, 1135, 261, 3890, 1578, 8526, 3778, 1311, 16, 1731, 8526, 3778, 924, 13, 288, 203, 3639, 1311, 273, 394, 1731, 1578, 8526, 12, 23, 1769, 203, 3639, 924, 273, 394, 1731, 8526, 12, 23, 1769, 203, 203, 3639, 1731, 3778, 3749, 1076, 1782, 273, 2236, 18, 588, 751, 12, 1126, 1782, 653, 1769, 203, 203, 3639, 309, 261, 10787, 1076, 1782, 18, 2469, 422, 374, 13, 288, 203, 5411, 1311, 63, 20, 65, 273, 526, 1782, 653, 31, 203, 5411, 924, 63, 20, 65, 273, 6091, 5664, 18, 11890, 5034, 21033, 12, 21, 1769, 203, 203, 5411, 1311, 63, 21, 65, 273, 511, 3118, 22, 1989, 18, 7163, 1076, 1046, 653, 24499, 12, 1126, 1782, 653, 16, 374, 1769, 203, 5411, 924, 63, 21, 65, 273, 6091, 5664, 18, 2867, 21033, 12, 16140, 1769, 203, 203, 5411, 1311, 63, 22, 65, 273, 852, 653, 31, 203, 5411, 924, 63, 22, 65, 273, 1731, 18, 16426, 12, 5831, 734, 16, 1731, 28, 12, 20, 10019, 203, 203, 5411, 2254, 5034, 526, 1782, 273, 24126, 18, 3922, 12, 10787, 1076, 1782, 16, 261, 11890, 5034, 10019, 203, 5411, 2254, 5034, 11653, 1782, 273, 526, 1782, 397, 404, 31, 203, 203, 5411, 1311, 63, 20, 65, 273, 526, 1782, 653, 31, 203, 5411, 924, 63, 20, 65, 273, 6091, 5664, 18, 11890, 5034, 21033, 12, 2704, 1076, 1782, 1769, 203, 203, 5411, 1311, 63, 21, 65, 273, 511, 3118, 22, 1989, 18, 7163, 1076, 1046, 653, 24499, 12, 1126, 1782, 653, 16, 11653, 2 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ACT496322' token contract // // Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187 // Symbol : ACT496322 // Name : ADZbuzz Thetruthaboutcancer.com Community Token // Total supply: 2000000 // Decimals : 8 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // (c) by Darwin Jayme with ADZbuzz Ltd. UK (adzbuzz.com) 2018. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // 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 = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ADZbuzzCommunityToken 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 ADZbuzzCommunityToken() public { symbol = "ACT496322"; name = "ADZbuzz Thetruthaboutcancer.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract ADZbuzzCommunityToken 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 ADZbuzzCommunityToken() public { symbol = "ACT496322"; name = "ADZbuzz Thetruthaboutcancer.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _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); 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] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } 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 { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1,518,812
[ 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, 565, 6835, 11738, 62, 70, 9510, 12136, 13352, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 3639, 533, 1071, 3273, 31, 203, 3639, 533, 1071, 225, 508, 31, 203, 3639, 2254, 28, 1071, 15105, 31, 203, 3639, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 377, 203, 3639, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 377, 203, 377, 203, 3639, 445, 11738, 62, 70, 9510, 12136, 13352, 1345, 1435, 1071, 288, 203, 5411, 3273, 273, 315, 6526, 7616, 26, 1578, 22, 14432, 203, 5411, 508, 273, 315, 1880, 62, 70, 9510, 935, 16354, 795, 21071, 4169, 2750, 18, 832, 16854, 13352, 3155, 14432, 203, 5411, 15105, 273, 1725, 31, 203, 5411, 389, 4963, 3088, 1283, 273, 576, 12648, 9449, 31, 203, 5411, 324, 26488, 63, 20, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 65, 273, 389, 4963, 3088, 1283, 31, 203, 5411, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 16, 389, 4963, 3088, 1283, 1769, 203, 3639, 289, 203, 377, 203, 377, 203, 3639, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-11-21 */ // File: contracts/common/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/ContextMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/ERC721Tradable.sol pragma solidity ^0.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // File: contracts/BitKoi.sol pragma solidity ^0.8.0; /** * @title BitKoi * BitKoi - a blockchain game at scale */ /// @title mix up two fish and find out which traits they should have, which includes the logic to enforce a "promo gene" in future gen0 releases abstract contract BitKoiTraitInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isBitKoiTraits() virtual public pure returns (bool); ///mix up the "genes" of the fish to see which genes our new fish will have function smooshFish(uint256 genes1, uint256 genes2, uint8 promoGene, uint256 targetBlock) virtual public returns (uint256); } /// @title A facet of BitKoiCore that manages special access privileges. /// Based on work from Cryptokitties and Axiom Zen (https://www.axiomzen.co) contract BitKoiAccessControl { // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address payable _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() virtual public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for KoiPond abstract contract BitKoiBase is BitKoiAccessControl, ERC721Tradable { /*** EVENTS ***/ /// @dev The Spawn event is fired whenever a new fish comes into existence. This obviously /// includes any time a fish is created through the spawnFish method, but it is also called /// when a new gen0 fish is created. event Spawn(uint256 fishId, uint64 timestamp); /*** DATA TYPES ***/ struct BitKoi { //a promotional gene that, when active, will enable this bitKoi to hatch with a specific trait //this is ONLY assigned for gen0 promo events uint8 promoGene; // The timestamp from the block when this fish came into existence. uint64 spawnTime; // The timestamp from the block when this fish was hatched. This also masks the traits for 'unhatched' BitKoi uint64 hatchTime; // The minimum timestamp after which this fish can engage in spawning // activities again. uint64 cooldownEndBlock; // The ID of the parents of this fish, set to 0 for gen0 fish. // With uint32 there's a limit of 4 billion fish uint32 parent1Id; uint32 parent2Id; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this fish. This starts at zero // for gen0 fish, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action. uint16 cooldownIndex; // The "generation number" of this fish. Fish minted by the KP contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other fish is the larger of the two generation // numbers of their parents, plus one. uint16 generation; // The fish's genetic code - this will never change for any fish. uint256 genes; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "cooldown" Designed such that the cooldown roughly /// doubles each time a fish is bred, encouraging owners not to just keep breeding the same fish over /// and over again. Caps out at one week (a fish can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the KoiFish struct for all KoiFish in existence. The ID /// of each fish is actually an index into this array. Fish 0 has an invalid genetic /// code and can't be used to produce offspring. BitKoi[] bitKoi; // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } abstract contract BitKoiOwnership is BitKoiBase { /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns( address _claimant, uint256 _tokenId ) internal view returns (bool) { return (ownerOf(_tokenId) == _claimant); } /// @notice Returns a list of all BitKoi IDs assigned to an address. /// @param _owner The owner whose BitKoi we are interested in. function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; uint256 tokenIndex; for (tokenIndex = 0; tokenIndex <= tokenCount - 1; tokenIndex++) { uint256 tokenId = tokenOfOwnerByIndex(_owner, tokenIndex); result[resultIndex] = tokenId; resultIndex++; } return result; } } } abstract contract BitKoiBreeding is BitKoiOwnership { event Hatch(address owner, uint256 fishId, uint64 hatchTime); uint256 public breedFee = 0 wei; uint256 public hatchFee = 0 wei; /// @dev The address of the sibling contract that is used to implement the genetic combination algorithm. BitKoiTraitInterface public bitKoiTraits; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setBitKoiTraitAddress(address _address) external onlyCEO { BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address); // NOTE: verify that a contract is what we expect it to be and not some random other one require(candidateContract.isBitKoiTraits()); // Set the new contract address bitKoiTraits = candidateContract; } /// @dev Checks that a given fish is able to breed. Requires that the /// current cooldown is finished function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the fish has a pending birth; there can be some period of time between the end // of the pregnacy timer and the spawn event. return _fish.cooldownEndBlock <= uint64(block.number); } /// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _koiFish A reference to the KoiFish in storage which needs its timer started. function _triggerCooldown(BitKoi storage _koiFish) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_koiFish.cooldownIndex < 13) { _koiFish.cooldownIndex += 1; } } // @dev Updates the minimum payment required for calling breedWith(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setBreedFee(uint256 val) external onlyCOO { breedFee = val; } // @dev Updates the minimum payment required for calling hatchFish(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setHatchFee(uint256 val) external onlyCOO { hatchFee = val; } /// @notice Checks that a given fish is able to breed (i.e. it is not /// in the middle of a cooldown). /// @param _koiId reference the id of the fish, any user can inquire about it function isReadyToBreed(uint256 _koiId) public view returns (bool) { require(_koiId > 0); BitKoi storage fish = bitKoi[_koiId]; return _isReadyToBreed(fish); } /// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _parent1 A reference to the Fish struct of the potential first parent /// @param _parent1Id The first parent's ID. /// @param _parent2 A reference to the Fish struct of the potential second parent /// @param _parent2Id The second parent's ID. function _isValidMatingPair( BitKoi storage _parent1, uint256 _parent1Id, BitKoi storage _parent2, uint256 _parent2Id ) private view returns(bool) { // A Fish can't breed with itself! if (_parent1Id == _parent2Id) { return false; } //the fish have to have genes if (_parent1.genes == 0 || _parent2.genes == 0) { return false; } //they both have to be hatched if (_parent1.hatchTime == 0 || _parent2.hatchTime == 0) { return false; } // Fish can't breed with their parents. if (_parent1.parent1Id == _parent2Id || _parent1.parent2Id == _parent2Id) { return false; } if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent1Id) { return false; } // OK the tx if either fish is gen zero (no parent found). if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) { return true; } // Fish can't breed with full or half siblings. if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) { return false; } if (_parent2.parent2Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) { return false; } // gtg return true; } /// @notice Checks to see if two BitKoi can breed together, including checks for /// ownership. Doesn't check that both BitKoi are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// @param _parent1Id The ID of the proposed first parent. /// @param _parent2Id The ID of the proposed second parent. function canBreedWith(uint256 _parent1Id, uint256 _parent2Id) external view returns(bool) { require(_parent1Id > 0); require(_parent2Id > 0); BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id); } /// @dev Internal utility function to initiate breeding (aka 'grinding nemo'). Assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) { // Grab a reference to the two Bitkoi we want to breed from storage. BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; // Determine the higher generation number of the two parents and use this for the new BitKoi uint16 parentGen = parent1.generation; if (parent2.generation > parent1.generation) { parentGen = parent2.generation; } // Transfer the breed fee to the CFO contract payable(address(cfoAddress)).transfer(msg.value); // Get new genes for the bitkoi but don't send in a promo gene - that's only for gen0 eggs uint256 newGenes = bitKoiTraits.smooshFish(parent1.genes, parent2.genes, 0, parent1.cooldownEndBlock); // Use the genes we just got to create a brand new BitKoi! uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, newGenes, false, 0, msg.sender); // Trigger the cooldown for both parents. _triggerCooldown(parent1); _triggerCooldown(parent2); return newFishId; } function breedWith(uint256 _parent1Id, uint256 _parent2Id) external payable whenNotPaused { // Checks for payment. require(msg.value >= breedFee); ///check to see if the caller owns both bitkoi require(_owns(msg.sender, _parent1Id)); require(_owns(msg.sender, _parent2Id)); // Grab a reference to the bitkoi parent BitKoi storage parent1 = bitKoi[_parent1Id]; // Make sure enough time has passed since the last time this fish was bred require(_isReadyToBreed(parent1)); // Grab a reference to the second parent BitKoi storage parent2 = bitKoi[_parent2Id]; // Make sure enough time has passed since the last time this bitkoi was bred require(_isReadyToBreed(parent2)); // Test that these bitkoi are a valid mating pair. require(_isValidMatingPair( parent1, _parent1Id, parent2, _parent2Id )); // All checks passed, smoosh 'em! _breedWith(_parent1Id, _parent2Id); } /// @dev An internal method that creates a new fish and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _parent1Id The fish ID of the first parent (zero for gen0) /// @param _parent2Id The fish ID of the second parent (zero for gen0) /// @param _generation The generation number of this fish, must be computed by caller. /// @param _genes The fish's genetic code. /// @param _promoGene The promo gene for special mint events /// @param _to The inital owner of this fish, must be non-zero (except for fish ID 0) function _createBitKoi( uint256 _parent1Id, uint256 _parent2Id, uint256 _generation, uint256 _genes, bool _hatchMe, uint8 _promoGene, address _to ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKoiFish() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_parent1Id == uint256(uint32(_parent1Id))); require(_parent2Id == uint256(uint32(_parent2Id))); require(_generation == uint256(uint16(_generation))); // New fish starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } uint64 hatchTime; if (_hatchMe){ hatchTime = uint64(block.timestamp); } BitKoi memory _bitKoi = BitKoi({ genes: _genes, promoGene: uint8(_promoGene), spawnTime: uint64(block.timestamp), hatchTime: hatchTime, cooldownEndBlock: 0, parent1Id: uint32(_parent1Id), parent2Id: uint32(_parent2Id), cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newBitKoiId = bitKoi.length; bitKoi.push(_bitKoi); // It's probably never going to happen, 4 billion fish is A LOT, but // let's just be 100% sure we never let this happen. require(newBitKoiId == uint256(uint32(newBitKoiId))); // This will assign ownership, and also emit the Transfer event as required per ERC721 _safeMint(_to, newBitKoiId); // emit the spawn event emit Spawn( newBitKoiId, uint64(_bitKoi.spawnTime) ); return newBitKoiId; } function hatchBitKoi(uint256 _fishId) external payable whenNotPaused { // Check for payment. require(msg.value >= hatchFee); // Ensure the caller owns the egg they want to hatch require(_owns(msg.sender, _fishId)); BitKoi storage fishToHatch = bitKoi[_fishId]; // Check to make sure the BitKoi isn't hatched yet require(fishToHatch.hatchTime == 0); fishToHatch.hatchTime = uint64(block.timestamp); // Transfer the hatch fee to the CFO contract payable(address(cfoAddress)).transfer(msg.value); // Announce that a new bitkoi has been hatched and trigger the render of the new asset emit Hatch(msg.sender, _fishId, fishToHatch.hatchTime); } } /// @title all functions related to creating fish (and their eggs) abstract contract BitKoiMinting is BitKoiBreeding { // Limits the number of fish the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5200; uint256 public constant GEN0_EGG_CREATION_LIMIT = 44800; // Counts the number of bitkoi the contract owner has minted. uint256 public promoCreatedCount; // Counts the number of bitkoi minted in public/private sales and releases uint256 public gen0CreatedCount; // Minting is not live to start bool public allowMinting = false; // Mint passes are not required to start bool public requireMintPass = false; // Require an address to have a token to mint uint public requiredHoldings = 0; // Set the price for minting a new BitKoi gen0 egg uint256 public gen0PromoPrice = 0 wei; // Set the cap of gen0 eggs - will increase progressively as mint events happen for releases uint256 public currentGen0Cap = 100; // The time the most current mint was started uint public mintEventStarted = block.timestamp; // The limit per wallet for this period uint public currentMintLimit = 0; mapping (address => uint) tokensAllowed; mapping (address => uint) lastMintParticipated; mapping (address => uint) tokensMintedThisPeriod; // allow direct sales of gen0 eggs function setAllowMinting(bool _val) external onlyCLevel { allowMinting = _val; } // update whether or not holders are required to mint function resetMintEventClock() external onlyCLevel { mintEventStarted = block.timestamp; } // update whether or not holders are required to mint function setHolderRequirement(uint _val) external onlyCLevel { requiredHoldings = _val; } // set current cap for sale - this can be raised later so new sales can be started w/ limits function setCurrentGen0Cap(uint256 _val) external onlyCOO { require (gen0CreatedCount + _val <= GEN0_EGG_CREATION_LIMIT); currentGen0Cap = _val; } // @dev Updates the minimum payment required for calling mintGen0Egg(). Can only /// be called by the CEO address. function setGen0PromoPrice(uint256 _val) external onlyCOO { gen0PromoPrice = _val; } // @dev Updates the max number of items an address can mint in the given period. Can only /// be called by the CEO address. function setRequireMintPasses(bool _val) external onlyCOO { requireMintPass = _val; } // Here we can limit the number of BitKoi eggs a wallet can mint in the current period function setMintLimitPerPeriod(uint _val) external onlyCOO { currentMintLimit = _val; } //set a gene that is promotional and garaunteed to be in a newly hatched egg during the promo period uint8 public currentPromoGene = 0; //enable the promo gene for future releases bool public currentPromoActive = false; function setPromoGene(uint8 _val) external onlyCLevel { currentPromoGene = _val; } function setPromoStatus(bool _status) external onlyCLevel { currentPromoActive = _status; } function whitelistMintPasses(address[] calldata _addressList, uint numberOfPasses) external onlyCOO { for (uint i = 0; i < _addressList.length; i++) { tokensAllowed[_addressList[i]] += numberOfPasses; } } function getAvailablePasses(address _address) public view returns(uint) { return tokensAllowed[_address]; } function getMintedThisPeriod(address _address) public view returns(uint){ return tokensMintedThisPeriod[_address]; } function getLastMintParticipated(address _address) public view returns(uint){ return lastMintParticipated[_address]; } function mintGen0Egg(uint numberToMint) external payable whenNotPaused { //make sure minting is active require (allowMinting); //ensure they're trying to mint at least 1 egg just so people don't waste gas require(numberToMint > 0); //make sure enough eth has been sent require (msg.value >= gen0PromoPrice * numberToMint); //make sure the new tokens will not exceed the overall cap require (gen0CreatedCount + numberToMint <= currentGen0Cap); //make sure we aren't over the limit for all gen0Eggs require (gen0CreatedCount + numberToMint <= GEN0_EGG_CREATION_LIMIT); // require the purchasesr to have at least the number of required tokens to mint require (balanceOf(msg.sender) >= requiredHoldings); //if a mint pass is required, ensure that they are whitelisted if (requireMintPass){ require(numberToMint <= tokensAllowed[msg.sender]); } //if the last mint they participated in was before this one, then clear the tokens minted for the current period if (lastMintParticipated[msg.sender] < mintEventStarted){ tokensMintedThisPeriod[msg.sender] = 0; } // check to see if they've minted in the current mint period if (currentMintLimit > 0){ require(numberToMint + tokensMintedThisPeriod[msg.sender] <= currentMintLimit); } uint8 promoGene; if (currentPromoActive){ promoGene = currentPromoGene; } //transfer the sale price less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(msg.value); for (uint i = 0; i < numberToMint; i++) { // Get new genes for the bitkoi but don't send in a promo gene uint256 newGenes = bitKoiTraits.smooshFish(0, 0, promoGene, block.number); _createBitKoi(0, 0, 0, newGenes, false, promoGene, msg.sender); gen0CreatedCount++; if (requireMintPass){ tokensAllowed[msg.sender]--; } tokensMintedThisPeriod[msg.sender]++; } // update the most recently participated in mint event lastMintParticipated[msg.sender] = mintEventStarted; } /// @dev we can create promo fish, up to a limit. Only callable by COO /// @param _genes the encoded genes of the fish to be created, any value is accepted /// @param _sendTo the future owner of the created fish. Default to contract COO function createPromoFish(uint256 _genes, address _sendTo, bool _hatched, uint8 promoGene) external onlyCOO { if (_sendTo == address(0)) { _sendTo = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createBitKoi(0, 0, 0, _genes, _hatched, promoGene, _sendTo); } } contract BitKoiCore is BitKoiMinting { constructor(address _proxyRegistryAddress) ERC721Tradable("BitKoi", "BITKOI", _proxyRegistryAddress) { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // the creator of the contract is also the initial COO cfoAddress = msg.sender; //start with an initial fish _createBitKoi(0, 0, 0, type(uint256).max, true, 0, address(msg.sender)); } string baseURI = "https://www.bitkoi.co/api/nft/"; string contractMainURI = "https://www.bitkoi.co"; function baseTokenURI() public view returns (string memory) { return baseURI; } function setBaseTokenURI(string memory _newBaseURI) public onlyCLevel { baseURI = _newBaseURI; } function setContractURI(string memory _newContractURI) public onlyCLevel { contractMainURI = _newContractURI; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } function contractURI() public view returns (string memory) { return contractMainURI; } function unpause() override public onlyCEO whenPaused { require(address(bitKoiTraits) != address(0)); // Actually unpause the contract. super.unpause(); } function withdrawBalance() external onlyCFO { payable(cfoAddress).transfer(address(this).balance); } /// @notice Returns all the relevant information about a specific fish. /// @param _id The ID of the fish we're looking up function getBitKoi(uint256 _id) external view returns ( bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint64 spawnTime, uint64 hatchTime, uint256 parent1Id, uint256 parent2Id, uint256 generation, uint256 cooldownEndBlock, uint256 genes, uint8 promoGene ) { BitKoi storage fish = bitKoi[_id]; isReady = (fish.cooldownEndBlock <= block.number); uint256 bitKoiGenes; if (fish.hatchTime > 0){ bitKoiGenes = fish.genes; } cooldownIndex = uint256(fish.cooldownIndex); nextActionAt = uint256(fish.cooldownEndBlock); spawnTime = uint64(fish.spawnTime); hatchTime = uint64(fish.hatchTime); parent1Id = uint256(fish.parent1Id); parent2Id = uint256(fish.parent2Id); generation = uint256(fish.generation); cooldownEndBlock = uint256(fish.cooldownEndBlock); genes = bitKoiGenes; promoGene = uint8(fish.promoGene); } }
@title A facet of BitKoiCore that manages special access privileges. Based on work from Cryptokitties and Axiom Zen (https://www.axiomzen.co) The addresses of the accounts (or contracts) that can execute actions within each roles. @dev Keeps track whether the contract is paused.
contract BitKoiAccessControl { address public ceoAddress; address public cfoAddress; address public cooAddress; bool public paused = false; } modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCFO(address payable _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() external onlyCLevel whenNotPaused { paused = true; } function unpause() virtual public onlyCEO whenPaused { paused = false; } }
2,415,330
[ 1, 37, 11082, 434, 6539, 47, 11359, 4670, 716, 20754, 281, 4582, 2006, 19583, 18, 25935, 603, 1440, 628, 22752, 601, 305, 88, 606, 471, 22516, 14642, 2285, 275, 261, 4528, 2207, 5591, 18, 651, 14642, 8396, 18, 2894, 13, 1021, 6138, 434, 326, 9484, 261, 280, 20092, 13, 716, 848, 1836, 4209, 3470, 1517, 4900, 18, 225, 10498, 87, 3298, 2856, 326, 6835, 353, 17781, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 6539, 47, 11359, 16541, 288, 203, 203, 565, 1758, 1071, 276, 4361, 1887, 31, 203, 565, 1758, 1071, 276, 617, 1887, 31, 203, 565, 1758, 1071, 1825, 83, 1887, 31, 203, 203, 565, 1426, 1071, 17781, 273, 629, 31, 203, 203, 97, 203, 565, 9606, 1338, 1441, 51, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 276, 4361, 1887, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 39, 3313, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 276, 617, 1887, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 3865, 51, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1825, 83, 1887, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 39, 2355, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 1825, 83, 1887, 747, 203, 5411, 1234, 18, 15330, 422, 276, 4361, 1887, 747, 203, 5411, 1234, 18, 15330, 422, 276, 617, 1887, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 444, 1441, 51, 12, 2867, 389, 2704, 1441, 51, 13, 3903, 1338, 1441, 51, 288, 203, 3639, 2583, 24899, 2704, 1441, 51, 480, 1758, 12, 20, 10019, 203, 203, 3639, 276, 4361, 1887, 273, 389, 2704, 1441, 51, 31, 203, 565, 289, 203, 203, 565, 445, 11440, 3313, 12, 2867, 8843, 429, 389, 2704, 39, 3313, 13, 3903, 1338, 1441, 51, 288, 203, 3639, 2583, 24899, 2704, 39, 3313, 480, 1758, 12, 2 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAOCurrency */ contract TAOCurrency is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals; // To differentiate denomination of TAO Currency uint256 public powerOfTen; uint256 public totalSupply; // This creates an array with all balances // address is the address of nameId, not the eth public address mapping (address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients // address is the address of TAO/Name Id, not eth public address event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt // address is the address of TAO/Name Id, not eth public address event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) { _transfer(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) { _mintToken(target, mintedAmount); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Position */ contract Position is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 4; uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4); uint256 public totalSupply; // Mapping from Name ID to bool value whether or not it has received Position Token mapping (address => bool) public receivedToken; // Mapping from Name ID to its total available balance mapping (address => uint256) public balanceOf; // Mapping from Name's TAO ID to its staked amount mapping (address => mapping(address => uint256)) public taoStakedBalance; // Mapping from TAO ID to its total staked amount mapping (address => uint256) public totalTAOStakedBalance; // This generates a public event on the blockchain that will notify clients event Mint(address indexed nameId, uint256 value); event Stake(address indexed nameId, address indexed taoId, uint256 value); event Unstake(address indexed nameId, address indexed taoId, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId` * @param _nameId Address to receive the tokens * @return true on success */ function mintToken(address _nameId) public inWhitelist returns (bool) { // Make sure _nameId has not received Position Token require (receivedToken[_nameId] == false); receivedToken[_nameId] = true; balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME); totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME); emit Mint(_nameId, MAX_SUPPLY_PER_NAME); return true; } /** * @dev Get staked balance of `_nameId` * @param _nameId The Name ID to be queried * @return total staked balance */ function stakedBalance(address _nameId) public view returns (uint256) { return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]); } /** * @dev Stake `_value` tokens on `_taoId` from `_nameId` * @param _nameId The Name ID that wants to stake * @param _taoId The TAO ID to stake * @param _value The amount to stake * @return true on success */ function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value); emit Stake(_nameId, _taoId, _value); return true; } /** * @dev Unstake `_value` tokens from `_nameId`'s `_taoId` * @param _nameId The Name ID that wants to unstake * @param _taoId The TAO ID to unstake * @param _value The amount to unstake * @return true on success */ function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value); balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance emit Unstake(_nameId, _taoId, _value); return true; } } /** * @title NameTAOLookup * */ contract NameTAOLookup is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; struct NameTAOInfo { string name; address nameTAOAddress; string parentName; uint256 typeId; // 0 = TAO. 1 = Name } uint256 public internalId; uint256 public totalNames; uint256 public totalTAOs; mapping (uint256 => NameTAOInfo) internal nameTAOInfos; mapping (bytes32 => uint256) internal internalIdLookup; /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a name exist in the list * @param _name The name to be checked * @return true if yes, false otherwise */ function isExist(string _name) public view returns (bool) { bytes32 _nameKey = keccak256(abi.encodePacked(_name)); return (internalIdLookup[_nameKey] > 0); } /** * @dev Add a new NameTAOInfo * @param _name The name of the Name/TAO * @param _nameTAOAddress The address of the Name/TAO * @param _parentName The parent name of the Name/TAO * @param _typeId If TAO = 0. Name = 1 * @return true on success */ function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) { require (bytes(_name).length > 0); require (_nameTAOAddress != address(0)); require (bytes(_parentName).length > 0); require (_typeId == 0 || _typeId == 1); require (!isExist(_name)); internalId++; bytes32 _nameKey = keccak256(abi.encodePacked(_name)); internalIdLookup[_nameKey] = internalId; NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId]; _nameTAOInfo.name = _name; _nameTAOInfo.nameTAOAddress = _nameTAOAddress; _nameTAOInfo.parentName = _parentName; _nameTAOInfo.typeId = _typeId; if (_typeId == 0) { totalTAOs++; } else { totalNames++; } return true; } /** * @dev Get the NameTAOInfo given a name * @param _name The name to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByName(string _name) public view returns (string, address, string, uint256) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Get the NameTAOInfo given an ID * @param _internalId The internal ID to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) { require (nameTAOInfos[_internalId].nameTAOAddress != address(0)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Return the nameTAOAddress given a _name * @param _name The name to be queried * @return the nameTAOAddress of the name */ function getAddressByName(string _name) public view returns (address) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return _nameTAOInfo.nameTAOAddress; } } /** * @title NamePublicKey */ contract NamePublicKey { using SafeMath for uint256; address public nameFactoryAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; struct PublicKey { bool created; address defaultKey; address[] keys; } // Mapping from nameId to its PublicKey mapping (address => PublicKey) internal publicKeys; // Event to be broadcasted to public when a publicKey is added to a Name event AddKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is removed from a Name event RemoveKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is set as default for a Name event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name ID exist in the list of Public Keys * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return publicKeys[_id].created; } /** * @dev Store the PublicKey info for a Name * @param _id The ID of the Name * @param _defaultKey The default public key for this Name * @return true on success */ function add(address _id, address _defaultKey) public isName(_id) onlyFactory returns (bool) { require (!isExist(_id)); require (_defaultKey != address(0)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.created = true; _publicKey.defaultKey = _defaultKey; _publicKey.keys.push(_defaultKey); return true; } /** * @dev Get total publicKeys count for a Name * @param _id The ID of the Name * @return total publicKeys count */ function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) { require (isExist(_id)); return publicKeys[_id].keys.length; } /** * @dev Check whether or not a publicKey exist in the list for a Name * @param _id The ID of the Name * @param _key The publicKey to check * @return true if yes. false otherwise */ function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) { require (isExist(_id)); require (_key != address(0)); PublicKey memory _publicKey = publicKeys[_id]; for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { return true; } } return false; } /** * @dev Add publicKey to list for a Name * @param _id The ID of the Name * @param _key The publicKey to be added */ function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (!isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); } /** * @dev Get default public key of a Name * @param _id The ID of the Name * @return the default public key */ function getDefaultKey(address _id) public isName(_id) view returns (address) { require (isExist(_id)); return publicKeys[_id].defaultKey; } /** * @dev Get list of publicKeys of a Name * @param _id The ID of the Name * @param _from The starting index * @param _to The ending index * @return list of publicKeys */ function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) { require (isExist(_id)); require (_from >= 0 && _to >= _from); PublicKey memory _publicKey = publicKeys[_id]; require (_publicKey.keys.length > 0); address[] memory _keys = new address[](_to.sub(_from).add(1)); if (_to > _publicKey.keys.length.sub(1)) { _to = _publicKey.keys.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _keys[i.sub(_from)] = _publicKey.keys[i]; } return _keys; } /** * @dev Remove publicKey from the list * @param _id The ID of the Name * @param _key The publicKey to be removed */ function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; // Can't remove default key require (_key != _publicKey.defaultKey); require (_publicKey.keys.length > 1); for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { delete _publicKey.keys[i]; _publicKey.keys.length--; uint256 _nonce = _nameFactory.incrementNonce(_id); break; } } require (_nonce > 0); emit RemoveKey(_id, _key, _nonce); } /** * @dev Set a publicKey as the default for a Name * @param _id The ID of the Name * @param _defaultKey The defaultKey to be set * @param _signatureV The V part of the signature for this update * @param _signatureR The R part of the signature for this update * @param _signatureS The S part of the signature for this update */ function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _defaultKey)); bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey)); require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.defaultKey = _defaultKey; uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SetDefaultKey(_id, _defaultKey, _nonce); } } /** * @title NameFactory * * The purpose of this contract is to allow node to create Name */ contract NameFactory is TheAO { using SafeMath for uint256; address public positionAddress; address public nameTAOVaultAddress; address public nameTAOLookupAddress; address public namePublicKeyAddress; Position internal _position; NameTAOLookup internal _nameTAOLookup; NameTAOPosition internal _nameTAOPosition; NamePublicKey internal _namePublicKey; address[] internal names; // Mapping from eth address to Name ID mapping (address => address) public ethAddressToNameId; // Mapping from Name ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when a Name is created event CreateName(address indexed ethAddress, address nameId, uint256 index, string name); /** * @dev Constructor function */ constructor(address _positionAddress, address _nameTAOVaultAddress) public { positionAddress = _positionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _position = Position(positionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update Name's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOLookup Address * @param _nameTAOLookupAddress The address of NameTAOLookup */ function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO { require (_nameTAOLookupAddress != address(0)); nameTAOLookupAddress = _nameTAOLookupAddress; _nameTAOLookup = NameTAOLookup(nameTAOLookupAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = NamePublicKey(namePublicKeyAddress); } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a Name * @param _nameId The ID of the Name * @return current nonce */ function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) { // Check if _nameId exist require (nonces[_nameId] > 0); nonces[_nameId]++; return nonces[_nameId]; } /** * @dev Create a Name * @param _name The name of the Name * @param _datHash The datHash to this Name's profile * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name */ function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); // Only one Name per ETH address require (ethAddressToNameId[msg.sender] == address(0)); // The address is the Name ID (which is also a TAO ID) address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[nameId]++; ethAddressToNameId[msg.sender] = nameId; // Store the name lookup information require (_nameTAOLookup.add(_name, nameId, 'human', 1)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(nameId, nameId, nameId, nameId)); // Store the public key information require (_namePublicKey.add(nameId, msg.sender)); names.push(nameId); // Need to mint Position token for this Name require (_position.mintToken(nameId)); emit CreateName(msg.sender, nameId, names.length.sub(1), _name); } /** * @dev Get Name information * @param _nameId The ID of the Name to be queried * @return The name of the Name * @return The originId of the Name (in this case, it's the creator node's ETH address) * @return The datHash of the Name * @return The database of the Name * @return The keyValue of the Name * @return The contentId of the Name * @return The typeId of the Name */ function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) { Name _name = Name(_nameId); return ( _name.name(), _name.originId(), _name.datHash(), _name.database(), _name.keyValue(), _name.contentId(), _name.typeId() ); } /** * @dev Get total Names count * @return total Names count */ function getTotalNamesCount() public view returns (uint256) { return names.length; } /** * @dev Get list of Name IDs * @param _from The starting index * @param _to The ending index * @return list of Name IDs */ function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from); require (names.length > 0); address[] memory _names = new address[](_to.sub(_from).add(1)); if (_to > names.length.sub(1)) { _to = names.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _names[i.sub(_from)] = names[i]; } return _names; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The name of the Name * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise */ function validateNameSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public view returns (bool) { require (_nameTAOLookup.isExist(_name)); address _nameId = _nameTAOLookup.getAddressByName(_name); address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_validateAddress != address(0)) { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _validateAddress && _namePublicKey.isKeyExist(_nameId, _validateAddress) ); } else { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _namePublicKey.getDefaultKey(_nameId) ); } } } /** * @title AOStringSetting * * This contract stores all AO string setting variables */ contract AOStringSetting is TheAO { // Mapping from settingId to it's actual string value mapping (uint256 => string) public settingValue; // Mapping from settingId to it's potential string value that is at pending state mapping (uint256 => string) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The string value to be set */ function setPendingValue(uint256 _settingId, string _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { string memory _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBytesSetting * * This contract stores all AO bytes32 setting variables */ contract AOBytesSetting is TheAO { // Mapping from settingId to it's actual bytes32 value mapping (uint256 => bytes32) public settingValue; // Mapping from settingId to it's potential bytes32 value that is at pending state mapping (uint256 => bytes32) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bytes32 value to be set */ function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bytes32 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOAddressSetting * * This contract stores all AO address setting variables */ contract AOAddressSetting is TheAO { // Mapping from settingId to it's actual address value mapping (uint256 => address) public settingValue; // Mapping from settingId to it's potential address value that is at pending state mapping (uint256 => address) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The address value to be set */ function setPendingValue(uint256 _settingId, address _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { address _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBoolSetting * * This contract stores all AO bool setting variables */ contract AOBoolSetting is TheAO { // Mapping from settingId to it's actual bool value mapping (uint256 => bool) public settingValue; // Mapping from settingId to it's potential bool value that is at pending state mapping (uint256 => bool) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bool value to be set */ function setPendingValue(uint256 _settingId, bool _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bool _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOUintSetting * * This contract stores all AO uint256 setting variables */ contract AOUintSetting is TheAO { // Mapping from settingId to it's actual uint256 value mapping (uint256 => uint256) public settingValue; // Mapping from settingId to it's potential uint256 value that is at pending state mapping (uint256 => uint256) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The uint256 value to be set */ function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { uint256 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOSettingAttribute * * This contract stores all AO setting data/state */ contract AOSettingAttribute is TheAO { NameTAOPosition internal _nameTAOPosition; struct SettingData { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created the setting address creatorTAOId; // The taoId that created the setting address associatedTAOId; // The taoId that the setting affects string settingName; // The human-readable name of the setting /** * 1 => uint256 * 2 => bool * 3 => address * 4 => bytes32 * 5 => string (catch all) */ uint8 settingType; bool pendingCreate; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting string settingDataJSON; // Catch-all } struct SettingState { uint256 settingId; // Identifier of this setting bool pendingUpdate; // State when setting is in process of being updated address updateAdvocateNameId; // The nameId of the Advocate that performed the update /** * A child of the associatedTAOId with the update Logos. * This tells the setting contract that there is a proposal TAO that is a Child TAO * of the associated TAO, which will be responsible for deciding if the update to the * setting is accepted or rejected. */ address proposalTAOId; /** * Signature of the proposalTAOId and update value by the associatedTAOId * Advocate's Name's address. */ string updateSignature; /** * The proposalTAOId moves here when setting value changes successfully */ address lastUpdateTAOId; string settingStateJSON; // Catch-all } struct SettingDeprecation { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created this deprecation address creatorTAOId; // The taoId that created this deprecation address associatedTAOId; // The taoId that the setting affects bool pendingDeprecated; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting bool migrated; // State when this setting is fully migrated // holds the pending new settingId value when a deprecation is set uint256 pendingNewSettingId; // holds the new settingId that has been approved by associatedTAOId uint256 newSettingId; // holds the pending new contract address for this setting address pendingNewSettingContractAddress; // holds the new contract address for this setting address newSettingContractAddress; } struct AssociatedTAOSetting { bytes32 associatedTAOSettingId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSetting { bytes32 creatorTAOSettingId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } struct AssociatedTAOSettingDeprecation { bytes32 associatedTAOSettingDeprecationId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSettingDeprecation { bytes32 creatorTAOSettingDeprecationId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } // Mapping from settingId to it's data mapping (uint256 => SettingData) internal settingDatas; // Mapping from settingId to it's state mapping (uint256 => SettingState) internal settingStates; // Mapping from settingId to it's deprecation info mapping (uint256 => SettingDeprecation) internal settingDeprecations; // Mapping from associatedTAOSettingId to AssociatedTAOSetting mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings; // Mapping from creatorTAOSettingId to CreatorTAOSetting mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings; // Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations; // Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations; /** * @dev Constructor function */ constructor(address _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Add setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return The ID of the "Associated" setting * @return The ID of the "Creator" setting */ function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) { // Store setting data/state require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData)); // Store the associatedTAOSetting info bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; _associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId; _associatedTAOSetting.associatedTAOId = _associatedTAOId; _associatedTAOSetting.settingId = _settingId; // Store the creatorTAOSetting info bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; _creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId; _creatorTAOSetting.creatorTAOId = _creatorTAOId; _creatorTAOSetting.settingId = _settingId; return (_associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Get Setting Data of a setting ID * @param _settingId The ID of the setting */ function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) { SettingData memory _settingData = settingDatas[_settingId]; return ( _settingData.settingId, _settingData.creatorNameId, _settingData.creatorTAOId, _settingData.associatedTAOId, _settingData.settingName, _settingData.settingType, _settingData.pendingCreate, _settingData.locked, _settingData.rejected, _settingData.settingDataJSON ); } /** * @dev Get Associated TAO Setting info * @param _associatedTAOSettingId The ID of the associated tao setting */ function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) { AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; return ( _associatedTAOSetting.associatedTAOSettingId, _associatedTAOSetting.associatedTAOId, _associatedTAOSetting.settingId ); } /** * @dev Get Creator TAO Setting info * @param _creatorTAOSettingId The ID of the creator tao setting */ function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) { CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; return ( _creatorTAOSetting.creatorTAOSettingId, _creatorTAOSetting.creatorTAOId, _creatorTAOSetting.settingId ); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingData.locked = false; } else { // Reject the setting _settingData.pendingCreate = false; _settingData.rejected = true; } return true; } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == false && _settingData.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId) ); // Update the setting data _settingData.pendingCreate = false; _settingData.locked = true; return true; } /** * @dev Store setting update data * @param _settingId The ID of the setting to be updated * @param _settingType The type of this setting * @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) { // Make sure setting is created SettingData memory _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.settingType == _settingType && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) && bytes(_updateSignature).length > 0 ); // Make sure setting is not in the middle of updating SettingState storage _settingState = settingStates[_settingId]; require (_settingState.pendingUpdate == false); // Make sure setting is not yet deprecated SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; if (_settingDeprecation.settingId == _settingId) { require (_settingDeprecation.migrated == false); } // Store the SettingState data _settingState.pendingUpdate = true; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; _settingState.proposalTAOId = _proposalTAOId; _settingState.updateSignature = _updateSignature; _settingState.settingStateJSON = _extraData; return true; } /** * @dev Get setting state * @param _settingId The ID of the setting */ function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) { SettingState memory _settingState = settingStates[_settingId]; return ( _settingState.settingId, _settingState.pendingUpdate, _settingState.updateAdvocateNameId, _settingState.proposalTAOId, _settingState.updateSignature, _settingState.lastUpdateTAOId, _settingState.settingStateJSON ); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _proposalTAOAdvocate The advocate of the proposal TAO * @param _approved Whether to approve or reject * @return true on success */ function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _proposalTAOAdvocate != address(0) && _proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId) ); if (_approved) { // Unlock the setting so that advocate of associatedTAOId can finalize the update _settingData.locked = false; } else { // Set pendingUpdate to false _settingState.pendingUpdate = false; _settingState.proposalTAOId = address(0); } return true; } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _associatedTAOAdvocate The advocate of the associated TAO * @return true on success */ function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == false && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0)); // Update the setting data _settingData.locked = true; // Update the setting state _settingState.pendingUpdate = false; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; address _proposalTAOId = _settingState.proposalTAOId; _settingState.proposalTAOId = address(0); _settingState.lastUpdateTAOId = _proposalTAOId; return true; } /** * @dev Add setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return The ID of the "Associated" setting deprecation * @return The ID of the "Creator" setting deprecation */ function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) { require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress)); // Store the associatedTAOSettingDeprecation info bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId; _associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId; _associatedTAOSettingDeprecation.settingId = _settingId; // Store the creatorTAOSettingDeprecation info bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId; _creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId; _creatorTAOSettingDeprecation.settingId = _settingId; return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Get Setting Deprecation info of a setting ID * @param _settingId The ID of the setting */ function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) { SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; return ( _settingDeprecation.settingId, _settingDeprecation.creatorNameId, _settingDeprecation.creatorTAOId, _settingDeprecation.associatedTAOId, _settingDeprecation.pendingDeprecated, _settingDeprecation.locked, _settingDeprecation.rejected, _settingDeprecation.migrated, _settingDeprecation.pendingNewSettingId, _settingDeprecation.newSettingId, _settingDeprecation.pendingNewSettingContractAddress, _settingDeprecation.newSettingContractAddress ); } /** * @dev Get Associated TAO Setting Deprecation info * @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation */ function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; return ( _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId, _associatedTAOSettingDeprecation.associatedTAOId, _associatedTAOSettingDeprecation.settingId ); } /** * @dev Get Creator TAO Setting Deprecation info * @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation */ function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; return ( _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId, _creatorTAOSettingDeprecation.creatorTAOId, _creatorTAOSettingDeprecation.settingId ); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == true && _settingDeprecation.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingDeprecation.locked = false; } else { // Reject the setting _settingDeprecation.pendingDeprecated = false; _settingDeprecation.rejected = true; } return true; } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == false && _settingDeprecation.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId) ); // Update the setting data _settingDeprecation.pendingDeprecated = false; _settingDeprecation.locked = true; _settingDeprecation.migrated = true; uint256 _newSettingId = _settingDeprecation.pendingNewSettingId; _settingDeprecation.pendingNewSettingId = 0; _settingDeprecation.newSettingId = _newSettingId; address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress; _settingDeprecation.pendingNewSettingContractAddress = address(0); _settingDeprecation.newSettingContractAddress = _newSettingContractAddress; return true; } /** * @dev Check if a setting exist and not rejected * @param _settingId The ID of the setting * @return true if exist. false otherwise */ function settingExist(uint256 _settingId) public view returns (bool) { SettingData memory _settingData = settingDatas[_settingId]; return (_settingData.settingId == _settingId && _settingData.rejected == false); } /** * @dev Get the latest ID of a deprecated setting, if exist * @param _settingId The ID of the setting * @return The latest setting ID */ function getLatestSettingId(uint256 _settingId) public view returns (uint256) { (,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId); while (_migrated && _newSettingId > 0) { _settingId = _newSettingId; (,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId); } return _settingId; } /***** Internal Method *****/ /** * @dev Store setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) { // Store setting data SettingData storage _settingData = settingDatas[_settingId]; _settingData.settingId = _settingId; _settingData.creatorNameId = _creatorNameId; _settingData.creatorTAOId = _creatorTAOId; _settingData.associatedTAOId = _associatedTAOId; _settingData.settingName = _settingName; _settingData.settingType = _settingType; _settingData.pendingCreate = true; _settingData.locked = true; _settingData.settingDataJSON = _extraData; // Store setting state SettingState storage _settingState = settingStates[_settingId]; _settingState.settingId = _settingId; return true; } /** * @dev Store setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return true on success */ function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) { // Make sure this setting exists require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false); // Make sure deprecation is not yet exist for this setting Id require (settingDeprecations[_settingId].creatorNameId == address(0)); // Make sure newSettingId exists require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false); // Make sure the settingType matches require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType); // Store setting deprecation info SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; _settingDeprecation.settingId = _settingId; _settingDeprecation.creatorNameId = _creatorNameId; _settingDeprecation.creatorTAOId = _creatorTAOId; _settingDeprecation.associatedTAOId = _associatedTAOId; _settingDeprecation.pendingDeprecated = true; _settingDeprecation.locked = true; _settingDeprecation.pendingNewSettingId = _newSettingId; _settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress; return true; } } /** * @title AOTokenInterface */ contract AOTokenInterface is TheAO, TokenERC20 { using SafeMath for uint256; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK TOKEN VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TokenERC20(initialSupply, tokenName, tokenSymbol) public { powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Prevent/Allow target from sending & receiving tokens * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mintToken(target, mintedAmount); return true; } /** * @dev Stake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` escrow balance * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive in escrow */ function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) { escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(this, target, mintedAmount); return true; } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network tokens to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * @dev Buy tokens from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(this, msg.sender, amount); } /** * @dev Sell `amount` tokens to contract * @param amount The amount of tokens to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = this; require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, this, amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title AOToken */ contract AOToken is AOTokenInterface { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; // AO Dev Team addresses to receive Primordial/Network Tokens address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52; address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28; AOSetting internal _aoSetting; /***** PRIMORDIAL TOKEN VARIABLES *****/ uint256 public primordialTotalSupply; uint256 public primordialTotalBought; uint256 public primordialSellPrice; uint256 public primordialBuyPrice; // Total available primordial token for sale 1,125,899,906,842,620 AO+ uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620; mapping (address => uint256) public primordialBalanceOf; mapping (address => mapping (address => uint256)) public primordialAllowance; // Mapping from owner's lot weighted multiplier to the amount of staked tokens mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance; event PrimordialTransfer(address indexed from, address indexed to, uint256 value); event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value); event PrimordialBurn(address indexed from, uint256 value); event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier); event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier); uint256 public totalLots; uint256 public totalBurnLots; uint256 public totalConvertLots; bool public networkExchangeEnded; /** * Stores Lot creation data (during network exchange) */ struct Lot { bytes32 lotId; uint256 multiplier; // This value is in 10^6, so 1000000 = 1 address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account burns primordial token */ struct BurnLot { bytes32 burnLotId; address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account converts network token to primordial token */ struct ConvertLot { bytes32 convertLotId; address lotOwner; uint256 tokenAmount; } // Mapping from Lot ID to Lot object mapping (bytes32 => Lot) internal lots; // Mapping from Burn Lot ID to BurnLot object mapping (bytes32 => BurnLot) internal burnLots; // Mapping from Convert Lot ID to ConvertLot object mapping (bytes32 => ConvertLot) internal convertLots; // Mapping from owner to list of owned lot IDs mapping (address => bytes32[]) internal ownedLots; // Mapping from owner to list of owned burn lot IDs mapping (address => bytes32[]) internal ownedBurnLots; // Mapping from owner to list of owned convert lot IDs mapping (address => bytes32[]) internal ownedConvertLots; // Mapping from owner to his/her current weighted multiplier mapping (address => uint256) internal ownerWeightedMultiplier; // Mapping from owner to his/her max multiplier (multiplier of account's first Lot) mapping (address => uint256) internal ownerMaxMultiplier; // Event to be broadcasted to public when a lot is created // multiplier value is in 10^6 to account for 6 decimal points event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount); // Event to be broadcasted to public when burn lot is created (when account burns primordial tokens) event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn); // Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens) event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress) AOTokenInterface(initialSupply, tokenName, tokenSymbol) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; _aoSetting = AOSetting(_aoSettingAddress); powerOfTen = 0; decimals = 0; setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token } /** * @dev Checks if buyer can buy primordial token */ modifier canBuyPrimordial(uint256 _sentAmount) { require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0); _; } /***** The AO ONLY METHODS *****/ /** * @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange * @param _aoDevTeam1 The first AO dev team address * @param _aoDevTeam2 The second AO dev team address */ function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO { aoDevTeam1 = _aoDevTeam1; aoDevTeam2 = _aoDevTeam2; } /***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/ /** * @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth * @param newPrimordialSellPrice Price users can sell to the contract * @param newPrimordialBuyPrice Price users can buy from the contract */ function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO { primordialSellPrice = newPrimordialSellPrice; primordialBuyPrice = newPrimordialBuyPrice; } /***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from` * @param _from The address of the target * @param _value The amount of Primordial tokens to stake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted balance is enough require (primordialBalanceOf[_from] >= _value); // Make sure the weighted multiplier is the same as account's current weighted multiplier require (_weightedMultiplier == ownerWeightedMultiplier[_from]); // Subtract from the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Add to the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value); emit PrimordialStake(_from, _value, _weightedMultiplier); return true; } /** * @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted staked balance is enough require (primordialStakedBalance[_from][_weightedMultiplier] >= _value); // Subtract from the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value); // Add to the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value); emit PrimordialUnstake(_from, _value, _weightedMultiplier); return true; } /** * @dev Send `_value` primordial tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /***** PUBLIC METHODS *****/ /***** Primordial TOKEN PUBLIC METHODS *****/ /** * @dev Buy Primordial tokens from contract by sending ether */ function buyPrimordialToken() public payable canBuyPrimordial(msg.value) { (uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value); require (tokenAmount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; } // Send the primordial token to buyer and reward AO devs _sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender); // Send remainder budget back to buyer if exist if (remainderBudget > 0) { msg.sender.transfer(remainderBudget); } } /** * @dev Send `_value` Primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(msg.sender, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Send `_value` Primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_value <= primordialAllowance[_from][msg.sender]); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount they can spend * @return true on success */ function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) { primordialAllowance[msg.sender][_spender] = _value; emit PrimordialApproval(msg.sender, _spender, _value); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approvePrimordialToken(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Remove `_value` Primordial tokens from the system irreversibly * and re-weight the account's multiplier after burn * @param _value The amount to burn * @return true on success */ function burnPrimordialToken(uint256 _value) public returns (bool success) { require (primordialBalanceOf[msg.sender] >= _value); require (calculateMaximumBurnAmount(msg.sender) >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value); primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(msg.sender, _value); emit PrimordialBurn(msg.sender, _value); return true; } /** * @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from` * and re-weight `_from`'s multiplier after burn * @param _from The address of sender * @param _value The amount to burn * @return true on success */ function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) { require (primordialBalanceOf[_from] >= _value); require (primordialAllowance[_from][msg.sender] >= _value); require (calculateMaximumBurnAmount(_from) >= _value); // Update `_from`'s multiplier ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(_from, _value); emit PrimordialBurn(_from, _value); return true; } /** * @dev Return all lot IDs owned by an address * @param _lotOwner The address of the lot owner * @return array of lot IDs */ function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedLots[_lotOwner]; } /** * @dev Return the total lots owned by an address * @param _lotOwner The address of the lot owner * @return total lots owner by the address */ function totalLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedLots[_lotOwner].length; } /** * @dev Return the lot information at a given index of the lots list of the requested owner * @param _lotOwner The address owning the lots list to be accessed * @param _index uint256 representing the index to be accessed of the requested lots list * @return id of the lot * @return The address of the lot owner * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) { require (_index < ownedLots[_lotOwner].length); Lot memory _lot = lots[ownedLots[_lotOwner][_index]]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return the lot information at a given ID * @param _lotId The lot ID in question * @return id of the lot * @return The lot owner address * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) { Lot memory _lot = lots[_lotId]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return all Burn Lot IDs owned by an address * @param _lotOwner The address of the burn lot owner * @return array of Burn Lot IDs */ function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedBurnLots[_lotOwner]; } /** * @dev Return the total burn lots owned by an address * @param _lotOwner The address of the burn lot owner * @return total burn lots owner by the address */ function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedBurnLots[_lotOwner].length; } /** * @dev Return the burn lot information at a given ID * @param _burnLotId The burn lot ID in question * @return id of the lot * @return The address of the burn lot owner * @return Primordial token amount in the burn lot */ function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) { BurnLot memory _burnLot = burnLots[_burnLotId]; return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount); } /** * @dev Return all Convert Lot IDs owned by an address * @param _lotOwner The address of the convert lot owner * @return array of Convert Lot IDs */ function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedConvertLots[_lotOwner]; } /** * @dev Return the total convert lots owned by an address * @param _lotOwner The address of the convert lot owner * @return total convert lots owner by the address */ function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedConvertLots[_lotOwner].length; } /** * @dev Return the convert lot information at a given ID * @param _convertLotId The convert lot ID in question * @return id of the lot * @return The address of the convert lot owner * @return Primordial token amount in the convert lot */ function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) { ConvertLot memory _convertLot = convertLots[_convertLotId]; return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount); } /** * @dev Return the average weighted multiplier of all lots owned by an address * @param _lotOwner The address of the lot owner * @return the weighted multiplier of the address (in 10 ** 6) */ function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) { return ownerWeightedMultiplier[_lotOwner]; } /** * @dev Return the max multiplier of an address * @param _target The address to query * @return the max multiplier of the address (in 10 ** 6) */ function maxMultiplierByAddress(address _target) public view returns (uint256) { return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0; } /** * @dev Calculate the primordial token multiplier, bonus network token percentage, and the * bonus network token amount on a given lot when someone purchases primordial token * during network exchange * @param _purchaseAmount The amount of primordial token intended to be purchased * @return The multiplier in (10 ** 6) * @return The bonus percentage * @return The amount of network token as bonus */ function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); return ( AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier), AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier), AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier) ); } /** * @dev Calculate the maximum amount of Primordial an account can burn * @param _account The address of the account * @return The maximum primordial token amount to burn */ function calculateMaximumBurnAmount(address _account) public view returns (uint256) { return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]); } /** * @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens * @param _account The address of the account * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) { require (calculateMaximumBurnAmount(_account) >= _amountToBurn); return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn); } /** * @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token * @param _account The address of the account * @param _amountToConvert The amount of network token to convert * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) { return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert); } /** * @dev Convert `_value` of network tokens to primordial tokens * and re-weight the account's multiplier after conversion * @param _value The amount to convert * @return true on success */ function convertToPrimordial(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value); // Burn network token burn(_value); // mint primordial token _mintPrimordialToken(msg.sender, _value); // Store convert lot info totalConvertLots++; // Generate convert lot Id bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots)); // Make sure no one owns this lot yet require (convertLots[convertLotId].lotOwner == address(0)); ConvertLot storage convertLot = convertLots[convertLotId]; convertLot.convertLotId = convertLotId; convertLot.lotOwner = msg.sender; convertLot.tokenAmount = _value; ownedConvertLots[msg.sender].push(convertLotId); emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]); return true; } /***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/ /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount of network tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transfer(_to, _value)); require (transferPrimordialToken(_to, _primordialValue)); return true; } /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transferFrom(_from, _to, _value)); require (transferPrimordialTokenFrom(_from, _to, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of network tokens they can spend * @return true on success */ function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.approve(_spender, _value)); require (approvePrimordialToken(_spender, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of Primordial Tokens they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) { require (super.approveAndCall(_spender, _value, _extraData)); require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burn(_value)); require (burnPrimordialToken(_primordialValue)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from` * @param _from The address of sender * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burnFrom(_from, _value)); require (burnPrimordialTokenFrom(_from, _primordialValue)); return true; } /***** INTERNAL METHODS *****/ /***** PRIMORDIAL TOKEN INTERNAL METHODS *****/ /** * @dev Calculate the amount of token the buyer will receive and remaining budget if exist * when he/she buys primordial token * @param _budget The amount of ETH sent by buyer * @return uint256 of the tokenAmount the buyer will receiver * @return uint256 of the remaining budget, if exist * @return bool whether or not the network exchange should end */ function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) { // Calculate the amount of tokens uint256 tokenAmount = _budget.div(primordialBuyPrice); // If we need to return ETH to the buyer, in the case // where the buyer sends more ETH than available primordial token to be purchased uint256 remainderEth = 0; // Make sure primordialTotalBought is not overflowing bool shouldEndNetworkExchange = false; if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) { tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); shouldEndNetworkExchange = true; remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice)); } return (tokenAmount, remainderEth, shouldEndNetworkExchange); } /** * @dev Actually sending the primordial token to buyer and reward AO devs accordingly * @param tokenAmount The amount of primordial token to be sent to buyer * @param to The recipient of the token */ function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal { (uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); // Update primordialTotalBought (uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount); primordialTotalBought = primordialTotalBought.add(tokenAmount); _createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount); // Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR()); if (aoDevTeam1 != address(0)) { _createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } if (aoDevTeam2 != address(0)) { _createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } _mintToken(theAO, theAONetworkTokenBonusAmount); } /** * @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account` * during network exchange, and reward `_networkTokenBonusAmount` if exist * @param _account Address of the lot owner * @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot * @param _multiplier The multiplier for this lot in (10 ** 6) * @param _networkTokenBonusAmount The network token bonus amount */ function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal { totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _multiplier; lot.lotOwner = _account; lot.tokenAmount = _primordialTokenAmount; ownedLots[_account].push(lotId); ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } _mintPrimordialToken(_account, lot.tokenAmount); _mintToken(_account, _networkTokenBonusAmount); emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount); } /** * @dev Create `mintedAmount` Primordial tokens and send it to `target` * @param target Address to receive the Primordial tokens * @param mintedAmount The amount of Primordial tokens it will receive */ function _mintPrimordialToken(address target, uint256 mintedAmount) internal { primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount); primordialTotalSupply = primordialTotalSupply.add(mintedAmount); emit PrimordialTransfer(0, this, mintedAmount); emit PrimordialTransfer(this, target, mintedAmount); } /** * @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account` * @param _account Address of lot owner * @param _tokenAmount The amount of tokens * @param _weightedMultiplier The multiplier of the lot (in 10^6) * @return bytes32 of new created lot ID */ function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) { require (_account != address(0)); require (_tokenAmount > 0); totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _weightedMultiplier; lot.lotOwner = _account; lot.tokenAmount = _tokenAmount; ownedLots[_account].push(lotId); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } return lotId; } /** * @dev Send `_value` Primordial tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient emit PrimordialTransfer(_from, _to, _value); assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances); return true; } /** * @dev Store burn lot information * @param _account The address of the account * @param _tokenAmount The amount of primordial tokens to burn */ function _createBurnLot(address _account, uint256 _tokenAmount) internal { totalBurnLots++; // Generate burn lot Id bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots)); // Make sure no one owns this lot yet require (burnLots[burnLotId].lotOwner == address(0)); BurnLot storage burnLot = burnLots[burnLotId]; burnLot.burnLotId = burnLotId; burnLot.lotOwner = _account; burnLot.tokenAmount = _tokenAmount; ownedBurnLots[_account].push(burnLotId); emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]); } /** * @dev Get setting variables * @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token * @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token * @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus * @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus */ function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier'); (uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier'); (uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier'); (uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier'); return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier); } } /** * @title AOTreasury * * The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations */ contract AOTreasury is TheAO { using SafeMath for uint256; bool public paused; bool public killed; struct Denomination { bytes8 name; address denominationAddress; } // Mapping from denomination index to Denomination object // The list is in order from lowest denomination to highest denomination // i.e, denominations[1] is the base denomination mapping (uint256 => Denomination) internal denominations; // Mapping from denomination ID to index of denominations mapping (bytes8 => uint256) internal denominationIndex; uint256 public totalDenominations; // Event to be broadcasted to public when a token exchange happens event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /** * @dev Checks if denomination is valid */ modifier isValidDenomination(bytes8 denominationName) { require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO adds denomination and the contract address associated with it * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationAddress != address(0)); require (denominationIndex[denominationName] == 0); totalDenominations++; // Make sure the new denomination is higher than the previous if (totalDenominations > 1) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress); AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen()); } denominations[totalDenominations].name = denominationName; denominations[totalDenominations].denominationAddress = denominationAddress; denominationIndex[denominationName] = totalDenominations; return true; } /** * @dev The AO updates denomination address or activates/deactivates the denomination * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominationAddress != address(0)); uint256 _denominationNameIndex = denominationIndex[denominationName]; AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); if (_denominationNameIndex > 1) { AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress); require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen()); } if (_denominationNameIndex < totalDenominations) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress); require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen()); } denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress; return true; } /***** PUBLIC METHODS *****/ /** * @dev Get denomination info based on name * @param denominationName The name to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominations[denominationIndex[denominationName]].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress); return ( denominations[denominationIndex[denominationName]].name, denominations[denominationIndex[denominationName]].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get denomination info by index * @param index The index to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) { require (index > 0 && index <= totalDenominations); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get base denomination info * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) { require (totalDenominations > 1); return getDenominationByIndex(1); } /** * @dev convert token from `denominationName` denomination to base denomination, * in this case it's similar to web3.toWei() functionality * * Example: * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount * * @param integerAmount uint256 of the integer amount to be converted * @param fractionAmount uint256 of the frational amount to be converted * @param denominationName bytes8 name of the token denomination * @return uint256 converted amount in base denomination from target denomination */ function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) { if (denominationName.length > 0 && denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0) && (integerAmount > 0 || fractionAmount > 0)) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint8 fractionNumDigits = _numDigits(fractionAmount); require (fractionNumDigits <= _denominationToken.decimals()); uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen()); if (_denominationToken.decimals() == 0) { fractionAmount = 0; } return baseInteger.add(fractionAmount); } else { return 0; } } /** * @dev convert token from base denomination to `denominationName` denomination, * in this case it's similar to web3.fromWei() functionality * @param integerAmount uint256 of the base amount to be converted * @param denominationName bytes8 name of the target token denomination * @return uint256 of the converted integer amount in target denomination * @return uint256 of the converted fraction amount in target denomination */ function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen()); uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen())); return (denominationInteger, denominationFraction); } /** * @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination * @param amount The amount of token to exchange * @param fromDenominationName The origin denomination * @param toDenominationName The target denomination */ function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) { require (amount > 0); Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]]; Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]]; AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress); AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress); require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount)); require (_toDenominationToken.mintToken(msg.sender, amount)); emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName); } /** * @dev Return the highest possible denomination given a base amount * @param amount The amount to be converted * @return the denomination short name * @return the denomination address * @return the integer amount at the denomination level * @return the fraction amount at the denomination level * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) { uint256 integerAmount; uint256 fractionAmount; uint256 index; for (uint256 i=totalDenominations; i>0; i--) { Denomination memory _denomination = denominations[i]; (integerAmount, fractionAmount) = fromBase(amount, _denomination.name); if (integerAmount > 0) { index = i; break; } } require (index > 0 && index <= totalDenominations); require (integerAmount > 0 || fractionAmount > 0); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, integerAmount, fractionAmount, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /***** INTERNAL METHOD *****/ /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function _numDigits(uint256 number) internal pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } contract Pathos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } contract Ethos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } /** * @title TAOController */ contract TAOController { NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of TAO ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } } // Store the name lookup for a Name/TAO /** * @title TAOFamily */ contract TAOFamily is TAOController { using SafeMath for uint256; address public taoFactoryAddress; TAOFactory internal _taoFactory; struct Child { address taoId; bool approved; // If false, then waiting for parent TAO approval bool connected; // If false, then parent TAO want to remove this child TAO } struct Family { address taoId; address parentId; // The parent of this TAO ID (could be a Name or TAO) uint256 childMinLogos; mapping (uint256 => Child) children; mapping (address => uint256) childInternalIdLookup; uint256 totalChildren; uint256 childInternalId; } mapping (address => Family) internal families; // Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce); // Event to be broadcasted to public when a TAO adds a child TAO event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce); // Event to be broadcasted to public when a TAO approves a child TAO event ApproveChild(address indexed taoId, address childId, uint256 nonce); // Event to be broadcasted to public when a TAO removes a child TAO event RemoveChild(address indexed taoId, address childId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == taoFactoryAddress); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a TAO ID exist in the list of families * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return families[_id].taoId != address(0); } /** * @dev Store the Family info for a TAO * @param _id The ID of the TAO * @param _parentId The parent ID of this TAO * @param _childMinLogos The min required Logos to create a TAO * @return true on success */ function add(address _id, address _parentId, uint256 _childMinLogos) public isTAO(_id) isNameOrTAO(_parentId) onlyFactory returns (bool) { require (!isExist(_id)); Family storage _family = families[_id]; _family.taoId = _id; _family.parentId = _parentId; _family.childMinLogos = _childMinLogos; return true; } /** * @dev Get Family info given a TAO ID * @param _id The ID of the TAO * @return the parent ID of this TAO (could be a Name/TAO) * @return the min required Logos to create a child TAO * @return the total child TAOs count */ function getFamilyById(address _id) public view returns (address, uint256, uint256) { require (isExist(_id)); Family memory _family = families[_id]; return ( _family.parentId, _family.childMinLogos, _family.totalChildren ); } /** * @dev Set min required Logos to create a child from this TAO * @param _childMinLogos The min Logos to set * @return the nonce for this transaction */ function updateChildMinLogos(address _id, uint256 _childMinLogos) public isTAO(_id) senderIsName() onlyAdvocate(_id) { require (isExist(_id)); Family storage _family = families[_id]; _family.childMinLogos = _childMinLogos; uint256 _nonce = _taoFactory.incrementNonce(_id); require (_nonce > 0); emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce); } /** * @dev Check if `_childId` is a child TAO of `_taoId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to check * @return true if yes. Otherwise return false. */ function isChild(address _taoId, address _childId) public view returns (bool) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family memory _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; return ( _childInternalId > 0 && _family.children[_childInternalId].approved && _family.children[_childInternalId].connected && _childFamily.parentId == _taoId ); } /** * @dev Add child TAO * @param _taoId The TAO ID to be added to * @param _childId The ID to be added to as child TAO */ function addChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) onlyFactory returns (bool) { require (!isChild(_taoId, _childId)); Family storage _family = families[_taoId]; require (_family.childInternalIdLookup[_childId] == 0); _family.childInternalId++; _family.childInternalIdLookup[_childId] = _family.childInternalId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); Child storage _child = _family.children[_family.childInternalId]; _child.taoId = _childId; // If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected // Otherwise, child TAO needs parent TAO approval address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId); address _childAdvocate = _nameTAOPosition.getAdvocate(_childId); if (_taoAdvocate == _childAdvocate) { _family.totalChildren++; _child.approved = true; _child.connected = true; Family storage _childFamily = families[_childId]; _childFamily.parentId = _taoId; } emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce); return true; } /** * @dev Advocate of `_taoId` approves child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be approved */ function approveChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family storage _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; require (_childInternalId > 0 && !_family.children[_childInternalId].approved && !_family.children[_childInternalId].connected ); _family.totalChildren++; Child storage _child = _family.children[_childInternalId]; _child.approved = true; _child.connected = true; _childFamily.parentId = _taoId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit ApproveChild(_taoId, _childId, _nonce); } /** * @dev Advocate of `_taoId` removes child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be removed */ function removeChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isChild(_taoId, _childId)); Family storage _family = families[_taoId]; _family.totalChildren--; Child storage _child = _family.children[_family.childInternalIdLookup[_childId]]; _child.connected = false; _family.childInternalIdLookup[_childId] = 0; Family storage _childFamily = families[_childId]; _childFamily.parentId = address(0); uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit RemoveChild(_taoId, _childId, _nonce); } /** * @dev Get list of child TAO IDs * @param _taoId The TAO ID to be checked * @param _from The starting index (start from 1) * @param _to The ending index, (max is childInternalId) * @return list of child TAO IDs */ function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) { require (isExist(_taoId)); Family storage _family = families[_taoId]; require (_from >= 1 && _to >= _from && _family.childInternalId >= _to); address[] memory _childIds = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0); } return _childIds; } } // Store TAO's child information /** * @title TAOFactory * * The purpose of this contract is to allow node to create TAO */ contract TAOFactory is TheAO, TAOController { using SafeMath for uint256; address[] internal taos; address public taoFamilyAddress; address public nameTAOVaultAddress; address public settingTAOId; NameTAOLookup internal _nameTAOLookup; TAOFamily internal _taoFamily; AOSetting internal _aoSetting; Logos internal _logos; // Mapping from TAO ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when Advocate creates a TAO event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSetting = AOSetting(_aoSettingAddress); _logos = Logos(_logosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update TAO's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the TAOFamily Address * @param _taoFamilyAddress The address of TAOFamily */ function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO { require (_taoFamilyAddress != address(0)); taoFamilyAddress = _taoFamilyAddress; _taoFamily = TAOFamily(taoFamilyAddress); } /** * @dev The AO set settingTAOId (The TAO ID that holds the setting values) * @param _settingTAOId The address of settingTAOId */ function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) { settingTAOId = _settingTAOId; } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a TAO * @param _taoId The ID of the TAO * @return current nonce */ function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) { // Check if _taoId exist require (nonces[_taoId] > 0); nonces[_taoId]++; return nonces[_taoId]; } /** * @dev Name creates a TAO * @param _name The name of the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _parentId The parent of this TAO (has to be a Name or TAO) * @param _childMinLogos The min required Logos to create a child from this TAO */ function createTAO( string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _parentId, uint256 _childMinLogos ) public senderIsName() isNameOrTAO(_parentId) { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); address _nameId = _nameFactory.ethAddressToNameId(msg.sender); uint256 _parentCreateChildTAOMinLogos; uint256 _createChildTAOMinLogos = _getSettingVariables(); if (AOLibrary.isTAO(_parentId)) { (, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId); } if (_parentCreateChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos); } else if (_createChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos); } // Create the TAO address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[taoId]++; // Store the name lookup information require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId)); require (_taoFamily.add(taoId, _parentId, _childMinLogos)); taos.push(taoId); emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoFamily.addChild(_parentId, taoId)); } } /** * @dev Get TAO information * @param _taoId The ID of the TAO to be queried * @return The name of the TAO * @return The origin Name ID that created the TAO * @return The name of Name that created the TAO * @return The datHash of the TAO * @return The database of the TAO * @return The keyValue of the TAO * @return The contentId of the TAO * @return The typeId of the TAO */ function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) { TAO _tao = TAO(_taoId); return ( _tao.name(), _tao.originId(), Name(_tao.originId()).name(), _tao.datHash(), _tao.database(), _tao.keyValue(), _tao.contentId(), _tao.typeId() ); } /** * @dev Get total TAOs count * @return total TAOs count */ function getTotalTAOsCount() public view returns (uint256) { return taos.length; } /** * @dev Get list of TAO IDs * @param _from The starting index * @param _to The ending index * @return list of TAO IDs */ function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from && taos.length > _to); address[] memory _taos = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _taos[i.sub(_from)] = taos[i]; } return _taos; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The Name of the TAO * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise * @return The name of the Name that created the signature * @return The Position of the Name that created the signature. * 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker */ function validateTAOSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) { address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) { return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name))); } else { return (false, "", 0); } } /***** INTERNAL METHOD *****/ /** * @dev Check whether or not the address recovered from the signature is valid * @param _validateAddress The ETH address to be validated (optional) * @param _signatureAddress The address recovered from the signature * @param _taoId The ID of the TAO * @param _nonce The signed uint256 nonce * @return true if valid. false otherwise */ function _isTAOSignatureAddressValid( address _validateAddress, address _signatureAddress, address _taoId, uint256 _nonce ) internal view returns (bool) { if (_validateAddress != address(0)) { return (_nonce == nonces[_taoId].add(1) && _signatureAddress == _validateAddress && _nameTAOPosition.senderIsPosition(_validateAddress, _taoId) ); } else { return ( _nonce == nonces[_taoId].add(1) && _nameTAOPosition.senderIsPosition(_signatureAddress, _taoId) ); } } /** * @dev Internal function to get the TAO Id by name * @param _name The name of the TAO * @return the TAO ID */ function _getTAOIdByName(string _name) internal view returns (address) { return _nameTAOLookup.getAddressByName(_name); } /** * @dev Get setting variables * @return createChildTAOMinLogos The minimum required Logos to create a TAO */ function _getSettingVariables() internal view returns (uint256) { (uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos'); return createChildTAOMinLogos; } } /** * @title NameTAOPosition */ contract NameTAOPosition is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; NameFactory internal _nameFactory; TAOFactory internal _taoFactory; struct Position { address advocateId; address listenerId; address speakerId; bool created; } mapping (address => Position) internal positions; // Event to be broadcasted to public when current Advocate of TAO sets New Advocate event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); nameTAOPositionAddress = address(this); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of a Name/TAO ID */ modifier onlyAdvocate(address _id) { require (senderIsAdvocate(msg.sender, _id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name/TAO ID exist in the list * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return positions[_id].created; } /** * @dev Check whether or not eth address is advocate of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsAdvocate(address _sender, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender)); } /** * @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsPosition(address _sender, address _id) public view returns (bool) { address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == address(0)) { return false; } else { return (positions[_id].created && (positions[_id].advocateId == _nameId || positions[_id].listenerId == _nameId || positions[_id].speakerId == _nameId ) ); } } /** * @dev Check whether or not _nameId is advocate of _id * @param _nameId The name ID to be checked * @param _id The ID to be checked * @return true if yes, false otherwise */ function nameIsAdvocate(address _nameId, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameId); } /** * @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO * @param _sender The ETH address that to check * @param _id The ID of the Name/TAO * @return 1 if Advocate. 2 if Listener. 3 if Speaker */ function determinePosition(address _sender, address _id) public view returns (uint256) { require (senderIsPosition(_sender, _id)); Position memory _position = positions[_id]; address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == _position.advocateId) { return 1; } else if (_nameId == _position.listenerId) { return 2; } else { return 3; } } /** * @dev Add Position for a Name/TAO * @param _id The ID of the Name/TAO * @param _advocateId The Advocate ID of the Name/TAO * @param _listenerId The Listener ID of the Name/TAO * @param _speakerId The Speaker ID of the Name/TAO * @return true on success */ function add(address _id, address _advocateId, address _listenerId, address _speakerId) public isNameOrTAO(_id) isName(_advocateId) isNameOrTAO(_listenerId) isNameOrTAO(_speakerId) onlyFactory returns (bool) { require (!isExist(_id)); Position storage _position = positions[_id]; _position.advocateId = _advocateId; _position.listenerId = _listenerId; _position.speakerId = _speakerId; _position.created = true; return true; } /** * @dev Get Name/TAO's Position info * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO * @return the Listener ID of Name/TAO * @return the Speaker ID of Name/TAO */ function getPositionById(address _id) public view returns (address, address, address) { require (isExist(_id)); Position memory _position = positions[_id]; return ( _position.advocateId, _position.listenerId, _position.speakerId ); } /** * @dev Get Name/TAO's Advocate * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO */ function getAdvocate(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.advocateId; } /** * @dev Get Name/TAO's Listener * @param _id The ID of the Name/TAO * @return the Listener ID of Name/TAO */ function getListener(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.listenerId; } /** * @dev Get Name/TAO's Speaker * @param _id The ID of the Name/TAO * @return the Speaker ID of Name/TAO */ function getSpeaker(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.speakerId; } /** * @dev Set Advocate for a TAO * @param _taoId The ID of the TAO * @param _newAdvocateId The new advocate ID to be set */ function setAdvocate(address _taoId, address _newAdvocateId) public isTAO(_taoId) isName(_newAdvocateId) senderIsName() onlyAdvocate(_taoId) { Position storage _position = positions[_taoId]; address _currentAdvocateId = _position.advocateId; _position.advocateId = _newAdvocateId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce); } /** * @dev Set Listener for a Name/TAO * @param _id The ID of the Name/TAO * @param _newListenerId The new listener ID to be set */ function setListener(address _id, address _newListenerId) public isNameOrTAO(_id) isNameOrTAO(_newListenerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Listener can only be a Name // If _id is a TAO, then new Listener can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newListenerId)); } Position storage _position = positions[_id]; address _currentListenerId = _position.listenerId; _position.listenerId = _newListenerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce); } /** * @dev Set Speaker for a Name/TAO * @param _id The ID of the Name/TAO * @param _newSpeakerId The new speaker ID to be set */ function setSpeaker(address _id, address _newSpeakerId) public isNameOrTAO(_id) isNameOrTAO(_newSpeakerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Speaker can only be a Name // If _id is a TAO, then new Speaker can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newSpeakerId)); } Position storage _position = positions[_id]; address _currentSpeakerId = _position.speakerId; _position.speakerId = _newSpeakerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce); } } /** * @title AOSetting * * This contract stores all AO setting variables */ contract AOSetting { address public aoSettingAttributeAddress; address public aoUintSettingAddress; address public aoBoolSettingAddress; address public aoAddressSettingAddress; address public aoBytesSettingAddress; address public aoStringSettingAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; AOSettingAttribute internal _aoSettingAttribute; AOUintSetting internal _aoUintSetting; AOBoolSetting internal _aoBoolSetting; AOAddressSetting internal _aoAddressSetting; AOBytesSetting internal _aoBytesSetting; AOStringSetting internal _aoStringSetting; uint256 public totalSetting; /** * Mapping from associatedTAOId's setting name to Setting ID. * * Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup, * use nested mapping to achieve the same result. * * The setting's name needs to be converted to bytes32 since solidity does not support mapping by string. */ mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup; // Mapping from updateHashKey to it's settingId mapping (bytes32 => uint256) public updateHashLookup; // Event to be broadcasted to public when a setting is created and waiting for approval event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId); // Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); // Event to be broadcasted to public when a proposed update for a setting is created event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId); // Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved); // Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate); // Event to be broadcasted to public when a setting deprecation is created and waiting for approval event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId); // Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _aoSettingAttributeAddress, address _aoUintSettingAddress, address _aoBoolSettingAddress, address _aoAddressSettingAddress, address _aoBytesSettingAddress, address _aoStringSettingAddress) public { aoSettingAttributeAddress = _aoSettingAttributeAddress; aoUintSettingAddress = _aoUintSettingAddress; aoBoolSettingAddress = _aoBoolSettingAddress; aoAddressSettingAddress = _aoAddressSettingAddress; aoBytesSettingAddress = _aoBytesSettingAddress; aoStringSettingAddress = _aoStringSettingAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress); _aoUintSetting = AOUintSetting(_aoUintSettingAddress); _aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress); _aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress); _aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress); _aoStringSetting = AOStringSetting(_aoStringSettingAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_settingName` of `_associatedTAOId` is taken */ modifier settingNameNotTaken(string _settingName, address _associatedTAOId) { require (settingNameExist(_settingName, _associatedTAOId) == false); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** Public Methods *****/ /** * @dev Check whether or not a setting name of an associatedTAOId exist * @param _settingName The human-readable name of the setting * @param _associatedTAOId The taoId that the setting affects * @return true if yes. false otherwise */ function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) { return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0); } /** * @dev Advocate of _creatorTAOId adds a uint setting * @param _settingName The human-readable name of the setting * @param _value The uint256 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoUintSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bool setting * @param _settingName The human-readable name of the setting * @param _value The bool value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBoolSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds an address setting * @param _settingName The human-readable name of the setting * @param _value The address value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoAddressSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bytes32 setting * @param _settingName The human-readable name of the setting * @param _value The bytes32 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBytesSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a string setting * @param _settingName The human-readable name of the setting * @param _value The string value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoStringSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingCreation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved)); (,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId); if (!_approved) { // Clear the settingName from nameSettingLookup so it can be added again in the future delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingCreation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate)); (,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoUintSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBoolSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoAddressSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBytesSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoStringSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */ function approveSettingUpdate(uint256 _settingId, bool _approved) public { address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId); require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved)); emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingUpdate(uint256 _settingId) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate)); (,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate); } /** * @dev Advocate of _creatorTAOId adds a setting deprecation * @param _settingId The ID of the setting to be deprecated * @param _newSettingId The new setting ID to route * @param _newSettingContractAddress The new setting contract address to route * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects */ function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) { (bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress); emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingDeprecation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved)); (,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingDeprecation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate)); (,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Get setting Id given an associatedTAOId and settingName * @param _associatedTAOId The ID of the AssociatedTAO * @param _settingName The name of the setting * @return the ID of the setting */ function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) { return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } /** * @dev Get setting values by setting ID. * Will throw error if the setting is not exist or rejected. * @param _settingId The ID of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) { require (_aoSettingAttribute.settingExist(_settingId)); _settingId = _aoSettingAttribute.getLatestSettingId(_settingId); return ( _aoUintSetting.settingValue(_settingId), _aoBoolSetting.settingValue(_settingId), _aoAddressSetting.settingValue(_settingId), _aoBytesSetting.settingValue(_settingId), _aoStringSetting.settingValue(_settingId) ); } /** * @dev Get setting values by taoId and settingName. * Will throw error if the setting is not exist or rejected. * @param _taoId The ID of the TAO * @param _settingName The name of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) { return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName)); } /***** Internal Method *****/ /** * @dev Store setting creation data * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal { // Make sure _settingType is in supported list require (_settingType >= 1 && _settingType <= 5); // Store nameSettingLookup nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting; // Store setting data/state (bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData); emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Move value of _settingId from pending variable to setting variable * @param _settingId The ID of the setting * @param _settingType The type of the setting */ function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal { // If settingType == uint256 if (_settingType == 1) { _aoUintSetting.movePendingToSetting(_settingId); } else if (_settingType == 2) { // Else if settingType == bool _aoBoolSetting.movePendingToSetting(_settingId); } else if (_settingType == 3) { // Else if settingType == address _aoAddressSetting.movePendingToSetting(_settingId); } else if (_settingType == 4) { // Else if settingType == bytes32 _aoBytesSetting.movePendingToSetting(_settingId); } else { // Else if settingType == string _aoStringSetting.movePendingToSetting(_settingId); } } } /** * @title AOEarning * * This contract stores the earning from staking/hosting content on AO */ contract AOEarning is TheAO { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; address public baseDenominationAddress; address public treasuryAddress; address public nameFactoryAddress; address public pathosAddress; address public ethosAddress; bool public paused; bool public killed; AOToken internal _baseAO; AOTreasury internal _treasury; NameFactory internal _nameFactory; Pathos internal _pathos; Ethos internal _ethos; AOSetting internal _aoSetting; // Total earning from staking content from all nodes uint256 public totalStakeContentEarning; // Total earning from hosting content from all nodes uint256 public totalHostContentEarning; // Total The AO earning uint256 public totalTheAOEarning; // Mapping from address to his/her earning from content that he/she staked mapping (address => uint256) public stakeContentEarning; // Mapping from address to his/her earning from content that he/she hosted mapping (address => uint256) public hostContentEarning; // Mapping from address to his/her network price earning // i.e, when staked amount = filesize mapping (address => uint256) public networkPriceEarning; // Mapping from address to his/her content price earning // i.e, when staked amount > filesize mapping (address => uint256) public contentPriceEarning; // Mapping from address to his/her inflation bonus mapping (address => uint256) public inflationBonusAccrued; struct Earning { bytes32 purchaseId; uint256 paymentEarning; uint256 inflationBonus; uint256 pathosAmount; uint256 ethosAmount; } // Mapping from address to earning from staking content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public stakeEarnings; // Mapping from address to earning from hosting content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public hostEarnings; // Mapping from purchase ID to earning for The AO mapping (bytes32 => Earning) public theAOEarnings; // Mapping from stake ID to it's total earning from staking mapping (bytes32 => uint256) public totalStakedContentStakeEarning; // Mapping from stake ID to it's total earning from hosting mapping (bytes32 => uint256) public totalStakedContentHostEarning; // Mapping from stake ID to it's total earning earned by The AO mapping (bytes32 => uint256) public totalStakedContentTheAOEarning; // Mapping from content host ID to it's total earning mapping (bytes32 => uint256) public totalHostContentEarningById; // Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earning is released from escrow // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when host's Name earns Ethos when a node buys a content event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _nameFactoryAddress The address of NameFactory * @param _pathosAddress The address of Pathos * @param _ethosAddress The address of Ethos */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; pathosAddress = _pathosAddress; ethosAddress = _ethosAddress; _aoSetting = AOSetting(_aoSettingAddress); _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _nameFactory = NameFactory(_nameFactoryAddress); _pathos = Pathos(_pathosAddress); _ethos = Ethos(_ethosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Calculate the content creator/host/The AO earning when request node buys the content. * Also at this stage, all of the earnings are stored in escrow * @param _buyer The request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function calculateEarning( address _buyer, bytes32 _purchaseId, uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) public isContractActive inWhitelist returns (bool) { // Split the payment earning between content creator and host and store them in escrow _escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); // Calculate the inflation bonus earning for content creator/node/The AO in escrow _escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); return true; } /** * @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID to check * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _stakeOwner The address of the stake owner * @param _host The address of the node that host the file * @return true on success */ function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) { // Release the earning in escrow for stake owner _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0); // Release the earning in escrow for host _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1); // Release the earning in escrow for The AO _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2); return true; } /***** INTERNAL METHODS *****/ /** * @dev Calculate the payment split for content creator/host and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal { (uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType); (uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning); _escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount); } /** * @dev Calculate the inflation bonus amount * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @return the bonus network amount */ function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); return _networkBonus.add(_primordialBonus); } /** * @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _inflationBonusAmount The amount of inflation bonus earning * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowInflationBonus( bytes32 _purchaseId, uint256 _inflationBonusAmount, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) internal { (, uint256 theAOCut,) = _getSettingVariables(); if (_inflationBonusAmount > 0) { // Store how much the content creator earns in escrow uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.inflationBonus = _stakeOwnerInflationBonus; require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus)); emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0); // Store how much the host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus); require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus)); emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1); // Store how much the The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus)); emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2); } else { emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0); emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1); emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2); } } /** * @dev Release the escrowed earning for a specific purchase ID for an account * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _account The address of account that made the earning (content creator/host) * @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO) */ function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal { // Make sure the recipient type is valid require (_recipientType >= 0 && _recipientType <= 2); uint256 _paymentEarning; uint256 _inflationBonus; uint256 _totalEarning; uint256 _pathosAmount; uint256 _ethosAmount; if (_recipientType == 0) { Earning storage _earning = stakeEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _pathosAmount = _earning.pathosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning); stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning); totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the content creator/stake owner with some Pathos require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount)); emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount); } else if (_recipientType == 1) { _earning = hostEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _ethosAmount = _earning.ethosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalHostContentEarning = totalHostContentEarning.add(_totalEarning); hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning); totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning); totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the host node with some Ethos require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount)); emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount); } else { _earning = theAOEarnings[_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalTheAOEarning = totalTheAOEarning.add(_totalEarning); inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning); } require (_baseAO.unescrowFrom(_account, _totalEarning)); emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType); } /** * @dev Get setting variables * @return inflationRate The rate to use when calculating inflation bonus * @return theAOCut The rate to use when calculating the AO earning * @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO */ function _getSettingVariables() internal view returns (uint256, uint256, uint256) { (uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate'); (uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut'); (uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate'); return (inflationRate, theAOCut, theAOEthosEarnedRate); } /** * @dev Calculate the payment split for content creator and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @return The stake owner's earning amount * @return The pathos earned from this transaction */ function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) { (uint256 inflationRate,,) = _getSettingVariables(); Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.purchaseId = _purchaseId; // Store how much the content creator (stake owner) earns in escrow // If content is AO Content Usage Type, stake owner earns 0% // and all profit goes to the serving host node _stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; // Pathos = Price X Node Share X Inflation Rate _stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning)); emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0); return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount); } /** * @dev Calculate the payment split for host node and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _host The address of the host node * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @param _stakeOwnerEarning The stake owner's earning amount * @return The ethos earned from this transaction */ function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); // Store how much the node host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.purchaseId = _purchaseId; _hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning); // Ethos = Price X Creator Share X Inflation Rate _hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); if (_isAOContentUsageType) { require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning)); } else { // If not AO Content usage type, we want to mint to the host require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning)); } emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1); return _hostEarning.ethosAmount; } /** * @dev Calculate the earning for The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _pathosAmount The amount of pathos earned by stake owner * @param _ethosAmount The amount of ethos earned by host node */ function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal { (,,uint256 theAOEthosEarnedRate) = _getSettingVariables(); // Store how much The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.purchaseId = _purchaseId; // Pathos + X% of Ethos _theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR())); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning)); emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2); } } /** * @title AOContent * * The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens * on his/her content */ contract AOContent is TheAO { using SafeMath for uint256; uint256 public totalContents; uint256 public totalContentHosts; uint256 public totalStakedContents; uint256 public totalPurchaseReceipts; address public settingTAOId; address public baseDenominationAddress; address public treasuryAddress; AOToken internal _baseAO; AOTreasury internal _treasury; AOEarning internal _earning; AOSetting internal _aoSetting; NameTAOPosition internal _nameTAOPosition; bool public paused; bool public killed; struct Content { bytes32 contentId; address creator; /** * baseChallenge is the content's PUBLIC KEY * When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY) * so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node * submit */ string baseChallenge; uint256 fileSize; bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content address taoId; bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO uint8 updateTAOContentStateV; bytes32 updateTAOContentStateR; bytes32 updateTAOContentStateS; string extraData; } struct StakedContent { bytes32 stakeId; bytes32 contentId; address stakeOwner; uint256 networkAmount; // total network token staked in base denomination uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination) uint256 primordialWeightedMultiplier; uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000 bool active; // true if currently staked, false when unstaked uint256 createdOnTimestamp; } struct ContentHost { bytes32 contentHostId; bytes32 stakeId; address host; /** * encChallenge is the content's PUBLIC KEY unique to the host */ string encChallenge; string contentDatKey; string metadataDatKey; } struct PurchaseReceipt { bytes32 purchaseId; bytes32 contentHostId; address buyer; uint256 price; uint256 amountPaidByBuyer; // total network token paid in base denomination uint256 amountPaidByAO; // total amount paid by AO string publicKey; // The public key provided by request node address publicAddress; // The public address provided by request node uint256 createdOnTimestamp; } // Mapping from Content index to the Content object mapping (uint256 => Content) internal contents; // Mapping from content ID to index of the contents list mapping (bytes32 => uint256) internal contentIndex; // Mapping from StakedContent index to the StakedContent object mapping (uint256 => StakedContent) internal stakedContents; // Mapping from stake ID to index of the stakedContents list mapping (bytes32 => uint256) internal stakedContentIndex; // Mapping from ContentHost index to the ContentHost object mapping (uint256 => ContentHost) internal contentHosts; // Mapping from content host ID to index of the contentHosts list mapping (bytes32 => uint256) internal contentHostIndex; // Mapping from PurchaseReceipt index to the PurchaseReceipt object mapping (uint256 => PurchaseReceipt) internal purchaseReceipts; // Mapping from purchase ID to index of the purchaseReceipts list mapping (bytes32 => uint256) internal purchaseReceiptIndex; // Mapping from buyer's content host ID to the buy ID // To check whether or not buyer has bought/paid for a content mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts; // Event to be broadcasted to public when `content` is stored event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType); // Event to be broadcasted to public when `stakeOwner` stakes a new content event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp); // Event to be broadcasted to public when a node hosts a content event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey); // Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage); // Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier); // Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId); // Event to be broadcasted to public when `stakeOwner` re-stakes an existing content event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier); // Event to be broadcasted to public when a request node buys a content event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp); // Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _earningAddress The address of AOEarning * @param _nameTAOPositionAddress The address of NameTAOPosition */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public { settingTAOId = _settingTAOId; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; nameTAOPositionAddress = _nameTAOPositionAddress; _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _earning = AOEarning(_earningAddress); _aoSetting = AOSetting(_aoSettingAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge */ function stakeAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage)); (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_aoContent, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _profitPercentage ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file */ function stakeCreativeCommonsContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize); (,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_creativeCommons, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) */ function stakeTAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, address _taoId) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require ( _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize && _nameTAOPosition.senderIsPosition(msg.sender, _taoId) ); (,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_taoContent, _taoId ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Set profit percentage on existing staked content * Will throw error if this is a Creative Commons/T(AO) Content * @param _stakeId The ID of the staked content * @param _profitPercentage The new value to be set */ function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive { require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR()); // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure we are updating profit percentage for AO Content only // Creative Commons/T(AO) Content has 0 profit percentage require (_isAOContentUsageType(_stakedContent.contentId)); _stakedContent.profitPercentage = _profitPercentage; emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage); } /** * @dev Set extra data on existing content * @param _contentId The ID of the content * @param _extraData some extra information to send to the contract for a content */ function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); Content storage _content = contents[contentIndex[_contentId]]; // Make sure the content creator is the same as the sender require (_content.creator == msg.sender); _content.extraData = _extraData; } /** * @dev Return content info at a given ID * @param _contentId The ID of the content * @return address of the creator * @return file size of the content * @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @return The TAO ID for this content (if this is a T(AO) Content) * @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO * @return The V part of signature that is used to update the TAO Content State * @return The R part of signature that is used to update the TAO Content State * @return The S part of signature that is used to update the TAO Content State * @return the extra information sent to the contract when creating a content */ function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) { // Make sure the content exist require (contentIndex[_contentId] > 0); Content memory _content = contents[contentIndex[_contentId]]; return ( _content.creator, _content.fileSize, _content.contentUsageType, _content.taoId, _content.taoContentState, _content.updateTAOContentStateV, _content.updateTAOContentStateR, _content.updateTAOContentStateS, _content.extraData ); } /** * @dev Return content host info at a given ID * @param _contentHostId The ID of the hosted content * @return The ID of the staked content * @return address of the host * @return the dat key of the content * @return the dat key of the content's metadata */ function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; return ( _contentHost.stakeId, _contentHost.host, _contentHost.contentDatKey, _contentHost.metadataDatKey ); } /** * @dev Return staked content information at a given ID * @param _stakeId The ID of the staked content * @return The ID of the content being staked * @return address of the staked content's owner * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the profit percentage of the content * @return status of the staked content * @return the timestamp when the staked content was created */ function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; return ( _stakedContent.contentId, _stakedContent.stakeOwner, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.active, _stakedContent.createdOnTimestamp ); } /** * @dev Unstake existing staked content and refund partial staked amount to the stake owner * Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to * the mininum required to pay the fileSize * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to unstake * @param _networkFractionAmount The fraction amount of network token to unstake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to unstake */ function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the staked content has enough balance to unstake require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize)); if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount); require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount); require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Unstake existing staked content and refund the total staked amount to the stake owner * @param _stakeId The ID of the staked content */ function unstakeContent(bytes32 _stakeId) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); _stakedContent.active = false; if (_stakedContent.networkAmount > 0) { uint256 _unstakeNetworkAmount = _stakedContent.networkAmount; _stakedContent.networkAmount = 0; require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_stakedContent.primordialAmount > 0) { uint256 _primordialAmount = _stakedContent.primordialAmount; uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier; _stakedContent.primordialAmount = 0; _stakedContent.primordialWeightedMultiplier = 0; require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier)); } emit UnstakeContent(_stakedContent.stakeOwner, _stakeId); } /** * @dev Stake existing content with more tokens (this is to increase the price) * * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier) */ function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount)); // Make sure we can stake primordial token // If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier` // i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) { require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier); } _stakedContent.active = true; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount); require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount); // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Determine the content price hosted by a host * @param _contentHostId The content host ID to be checked * @return the price of the content */ function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) { // Make sure content host exist require (contentHostIndex[_contentHostId] > 0); bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure content is currently staked require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); return _stakedContent.networkAmount.add(_stakedContent.primordialAmount); } /** * @dev Determine the how much the content is paid by AO given a contentHostId * @param _contentHostId The content host ID to be checked * @return the amount paid by AO */ function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) { bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; if (_isAOContentUsageType(_contentId)) { return 0; } else { return contentHostPrice(_contentHostId); } } /** * @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content * @param _contentHostId The ID of hosted content * @param _networkIntegerAmount The integer amount of network token to pay * @param _networkFractionAmount The fraction amount of network token to pay * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _publicKey The public key of the request node * @param _publicAddress The public address of the request node */ function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); // Make sure public key is not empty require (bytes(_publicKey).length > 0); // Make sure public address is valid require (_publicAddress != address(0)); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]]; // Make sure the content currently has stake require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the buyer has not bought this content previously require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0); // Make sure the token amount can pay for the content price if (_isAOContentUsageType(_stakedContent.contentId)) { require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination)); } // Increment totalPurchaseReceipts; totalPurchaseReceipts++; // Generate purchaseId bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId)); PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts]; // Make sure the node doesn't buy the same content twice require (_purchaseReceipt.buyer == address(0)); _purchaseReceipt.purchaseId = _purchaseId; _purchaseReceipt.contentHostId = _contentHostId; _purchaseReceipt.buyer = msg.sender; // Update the receipt with the correct network amount _purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount); _purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId); _purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO); _purchaseReceipt.publicKey = _publicKey; _purchaseReceipt.publicAddress = _publicAddress; _purchaseReceipt.createdOnTimestamp = now; purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts; buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId; // Calculate content creator/host/The AO earning from this purchase and store them in escrow require (_earning.calculateEarning( msg.sender, _purchaseId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.stakeOwner, _contentHost.host, _isAOContentUsageType(_stakedContent.contentId) )); emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp); } /** * @dev Return purchase receipt info at a given ID * @param _purchaseId The ID of the purchased content * @return The ID of the content host * @return address of the buyer * @return price of the content * @return amount paid by AO * @return amount paid by Buyer * @return request node's public key * @return request node's public address * @return created on timestamp */ function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; return ( _purchaseReceipt.contentHostId, _purchaseReceipt.buyer, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp ); } /** * @dev Request node wants to become a distribution node after buying the content * Also, if this transaction succeeds, contract will release all of the earnings that are * currently in escrow for content creator/host/The AO */ function becomeHost( bytes32 _purchaseId, uint8 _baseChallengeV, bytes32 _baseChallengeR, bytes32 _baseChallengeS, string _encChallenge, string _contentDatKey, string _metadataDatKey ) public isContractActive { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; // Make sure the purchase receipt owner is the same as the sender require (_purchaseReceipt.buyer == msg.sender); // Verify that the file is not tampered by validating the base challenge signature // The signed base challenge key should match the one from content creator Content memory _content = contents[contentIndex[_contentId]]; require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress); _hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey); // Release earning from escrow require (_earning.releaseEarning( _stakeId, _purchaseReceipt.contentHostId, _purchaseId, (_purchaseReceipt.amountPaidByBuyer > _content.fileSize), stakedContents[stakedContentIndex[_stakeId]].stakeOwner, contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host) ); } /** * @dev Update the TAO Content State of a T(AO) Content * @param _contentId The ID of the Content * @param _taoId The ID of the TAO that initiates the update * @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO * @param _updateTAOContentStateV The V part of the signature for this update * @param _updateTAOContentStateR The R part of the signature for this update * @param _updateTAOContentStateS The S part of the signature for this update */ function updateTAOContentState( bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _updateTAOContentStateV, bytes32 _updateTAOContentStateR, bytes32 _updateTAOContentStateS ) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); require (AOLibrary.isTAO(_taoId)); (,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables(); require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO); address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS); Content storage _content = contents[contentIndex[_contentId]]; // Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId)); require (_content.contentUsageType == _contentUsageType_taoContent); _content.taoContentState = _taoContentState; _content.updateTAOContentStateV = _updateTAOContentStateV; _content.updateTAOContentStateR = _updateTAOContentStateR; _content.updateTAOContentStateS = _updateTAOContentStateS; emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState); } /***** INTERNAL METHODS *****/ /** * @dev Store the content information (content creation during staking) * @param _creator the address of the content creator * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _fileSize The size of the file * @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) * @return the ID of the content */ function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) { // Increment totalContents totalContents++; // Generate contentId bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents)); Content storage _content = contents[totalContents]; // Make sure the node does't store the same content twice require (_content.creator == address(0)); (,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables(); _content.contentId = _contentId; _content.creator = _creator; _content.baseChallenge = _baseChallenge; _content.fileSize = _fileSize; _content.contentUsageType = _contentUsageType; // If this is a TAO Content if (_contentUsageType == contentUsageType_taoContent) { _content.taoContentState = taoContentState_submitted; _content.taoId = _taoId; } contentIndex[_contentId] = totalContents; emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType); return _content.contentId; } /** * @dev Add the distribution node info that hosts the content * @param _host the address of the host * @param _stakeId The ID of the staked content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata */ function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal { require (bytes(_encChallenge).length > 0); require (bytes(_contentDatKey).length > 0); require (bytes(_metadataDatKey).length > 0); require (stakedContentIndex[_stakeId] > 0); // Increment totalContentHosts totalContentHosts++; // Generate contentId bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId)); ContentHost storage _contentHost = contentHosts[totalContentHosts]; // Make sure the node doesn't host the same content twice require (_contentHost.host == address(0)); _contentHost.contentHostId = _contentHostId; _contentHost.stakeId = _stakeId; _contentHost.host = _host; _contentHost.encChallenge = _encChallenge; _contentHost.contentDatKey = _contentDatKey; _contentHost.metadataDatKey = _metadataDatKey; contentHostIndex[_contentHostId] = totalContentHosts; emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey); } /** * @dev actual staking the content * @param _stakeOwner the address that stake the content * @param _contentId The ID of the content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return the newly created staked content ID */ function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) { // Increment totalStakedContents totalStakedContents++; // Generate stakeId bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId)); StakedContent storage _stakedContent = stakedContents[totalStakedContents]; // Make sure the node doesn't stake the same content twice require (_stakedContent.stakeOwner == address(0)); _stakedContent.stakeId = _stakeId; _stakedContent.contentId = _contentId; _stakedContent.stakeOwner = _stakeOwner; _stakedContent.profitPercentage = _profitPercentage; _stakedContent.active = true; _stakedContent.createdOnTimestamp = now; stakedContentIndex[_stakeId] = totalStakedContents; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { _stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _primordialAmount; // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp); return _stakedContent.stakeId; } /** * @dev Get setting variables * @return contentUsageType_aoContent Content Usage Type = AO Content * @return contentUsageType_creativeCommons Content Usage Type = Creative Commons * @return contentUsageType_taoContent Content Usage Type = T(AO) Content * @return taoContentState_submitted TAO Content State = Submitted * @return taoContentState_pendingReview TAO Content State = Pending Review * @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO */ function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) { (,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent'); (,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons'); (,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent'); (,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted'); (,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview'); (,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO'); return ( contentUsageType_aoContent, contentUsageType_creativeCommons, contentUsageType_taoContent, taoContentState_submitted, taoContentState_pendingReview, taoContentState_acceptedToTAO ); } /** * @dev Check whether or not the content is of AO Content Usage Type * @param _contentId The ID of the content * @return true if yes. false otherwise */ function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) { (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } contract Logos is TAOCurrency { NameTAOPosition internal _nameTAOPosition; // Mapping of a Name ID to the amount of Logos positioned by others to itself // address is the address of nameId, not the eth public address mapping (address => uint256) public positionFromOthers; // Mapping of Name ID to other Name ID and the amount of Logos positioned by itself mapping (address => mapping(address => uint256)) public positionToOthers; // Mapping of a Name ID to the total amount of Logos positioned by itself to others mapping (address => uint256) public totalPositionToOthers; // Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned mapping (address => mapping(address => uint256)) public advocatedTAOLogos; // Mapping of a Name ID to the total amount of Logos earned from advocated TAO mapping (address => uint256) public totalAdvocatedTAOLogos; // Event broadcasted to public when `from` address position `value` Logos to `to` event PositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `from` address unposition `value` Logos from `to` event UnpositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId` event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount); // Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId` event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress) TAOCurrency(initialSupply, tokenName, tokenSymbol) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of _id */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Get the total sum of Logos for an address * @param _target The address to check * @return The total sum of Logos (own + positioned + advocated TAOs) */ function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) { return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]); } /** * @dev `_from` Name position `_value` Logos onto `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to position * @return true on success */ function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't position Logos to itself require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value); positionFromOthers[_to] = positionFromOthers[_to].add(_value); emit PositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers); assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance); return true; } /** * @dev `_from` Name unposition `_value` Logos from `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to unposition * @return true on success */ function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't unposition Logos to itself require (positionToOthers[_from][_to] >= _value); uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value); positionFromOthers[_to] = positionFromOthers[_to].sub(_value); emit UnpositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers); assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance); return true; } /** * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate * @param _taoId The ID of the advocated TAO * @param _amount the amount to reward * @return true on success */ function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) { require (_amount > 0); address _nameId = _nameTAOPosition.getAdvocate(_taoId); advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount); emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount); return true; } /** * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId` * @param _fromNameId The ID of the Name that sends the Logos * @param _toNameId The ID of the Name that receives the Logos * @param _taoId The ID of the advocated TAO * @return true on success */ function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) { require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId)); require (advocatedTAOLogos[_fromNameId][_taoId] > 0); require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]); uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId]; advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount); totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount); advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount); emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount); return true; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev Check whether or not content creator can stake a content based on the provided params * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return true if yes. false otherwise */ function canStake(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public view returns (bool) { return ( bytes(_baseChallenge).length > 0 && bytes(_encChallenge).length > 0 && bytes(_contentDatKey).length > 0 && bytes(_metadataDatKey).length > 0 && _fileSize > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) && _stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true && _profitPercentage <= _PERCENTAGE_DIVISOR ); } /** * @dev Check whether or the requested unstake amount is valid * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @param _stakedNetworkAmount The current staked network token amount * @param _stakedPrimordialAmount The current staked primordial token amount * @param _stakedFileSize The file size of the staked content * @return true if can unstake, false otherwise */ function canUnstakePartial( address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _stakedNetworkAmount, uint256 _stakedPrimordialAmount, uint256 _stakedFileSize) public view returns (bool) { if ( (_denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && _stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) ) || _stakedPrimordialAmount < _primordialAmount || ( _denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize) ) || ( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize) ) { return false; } else { return true; } } /** * @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _isAOContentUsageType whether or not the content is of AO Content usage type * @param _fileSize The size of the file * @param _stakedAmount The total staked amount * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @return true when the amount is sufficient, false otherwise */ function canStakeExisting( address _treasuryAddress, bool _isAOContentUsageType, uint256 _fileSize, uint256 _stakedAmount, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount ) public view returns (bool) { if (_isAOContentUsageType) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize; } else { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize; } } /** * @dev Check whether the network token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _price The price of the content * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @return true when the amount is sufficient, false otherwise */ function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price; } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial token balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial token amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedTokens.div(_totalTokens); } else { return _additionalWeightedMultiplier; } } /** * @dev Return the address that signed the message when a node wants to become a host * @param _callingContractAddress the address of the calling contract * @param _message the message that was signed * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the address that signed the TAO content state update * @param _callingContractAddress the address of the calling contract * @param _contentId the ID of the content * @param _taoId the ID of the TAO * @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the staking and earning information of a stake ID * @param _contentAddress The address of AOContent * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId); (uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier, totalStakeEarning, totalHostEarning, totalTheAOEarning ); } /** * @dev Return the staking information of a stake ID * @param _contentAddress The address of AOContent * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content */ function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { (,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier ); } /** * @dev Return the earning information of a stake ID * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { return ( AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId) ); } /** * @dev Calculate the primordial token multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network token on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Token Bonus Multiplier = Bs * Ending Network Token Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network token on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network token bonus amount */ uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkTokenBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network token to primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network token to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev Get TAO Currency Balances given a nameId * @param _nameId The ID of the Name * @param _logosAddress The address of Logos * @param _ethosAddress The address of Ethos * @param _pathosAddress The address of Pathos * @return sum Logos balance of the Name ID * @return Ethos balance of the Name ID * @return Pathos balance of the Name ID */ function getTAOCurrencyBalances( address _nameId, address _logosAddress, address _ethosAddress, address _pathosAddress ) public view returns (uint256, uint256, uint256) { return ( Logos(_logosAddress).sumBalanceOf(_nameId), TAOCurrency(_ethosAddress).balanceOf(_nameId), TAOCurrency(_pathosAddress).balanceOf(_nameId) ); } /** * @dev Return the address that signed the data and nonce when validating signature * @param _callingContractAddress the address of the calling contract * @param _data the data that was signed * @param _nonce The signed uint256 nonce * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce)); return ecrecover(_hash, _v, _r, _s); } /***** Internal Methods *****/ /** * @dev Check whether the network token and/or primordial token is adequate to pay for the filesize * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _fileSize The size of the file * @return true when the amount is sufficient, false otherwise */ function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize; } } contract Epiphany is TheAO { string public what; string public when; string public why; string public who; address public where; string public aSign; string public logos; constructor() public { what = 'The AO'; when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.'; why = 'To Hear, See, and Speak the Human inside Humanity.'; who = 'You. Set the world, Free. – Truth'; aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf'; logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32'; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Set `where` value * @param _where The new value to be set */ function setWhere(address _where) public onlyTheAO { where = _where; } }
* @title TAOController/
contract TAOController { NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } }
10,007,377
[ 1, 9833, 51, 2933, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 399, 20463, 2933, 288, 203, 202, 461, 1733, 2713, 389, 529, 1733, 31, 203, 202, 461, 9833, 51, 2555, 2713, 389, 529, 9833, 51, 2555, 31, 203, 203, 202, 12316, 12, 2867, 389, 529, 1733, 1887, 16, 1758, 389, 529, 9833, 51, 2555, 1887, 13, 1071, 288, 203, 202, 202, 67, 529, 1733, 273, 1770, 1733, 24899, 529, 1733, 1887, 1769, 203, 202, 202, 67, 529, 9833, 51, 2555, 273, 1770, 9833, 51, 2555, 24899, 529, 9833, 51, 2555, 1887, 1769, 203, 202, 97, 203, 203, 202, 20597, 353, 9833, 51, 12, 2867, 389, 2351, 83, 548, 13, 288, 203, 202, 202, 6528, 261, 37, 1741, 495, 3345, 18, 291, 9833, 51, 24899, 2351, 83, 548, 10019, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 30430, 12, 2867, 389, 529, 548, 13, 288, 203, 202, 202, 6528, 261, 37, 1741, 495, 3345, 18, 291, 461, 24899, 529, 548, 10019, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 30430, 1162, 9833, 51, 12, 2867, 389, 350, 13, 288, 203, 202, 202, 6528, 261, 37, 1741, 495, 3345, 18, 291, 461, 24899, 350, 13, 747, 432, 1741, 495, 3345, 18, 291, 9833, 51, 24899, 350, 10019, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 9606, 5793, 2520, 461, 1435, 288, 203, 202, 202, 6528, 261, 67, 529, 1733, 18, 546, 1887, 774, 461, 548, 12, 3576, 18, 15330, 13, 480, 1758, 12, 20, 10019, 203, 202, 202, 67, 31, 203, 202, 289, 203, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-09-18 */ /** *Submitted for verification at Etherscan.io on 2021-08-23 */ // Sources flattened with hardhat v2.4.3 https://hardhat.org // File @openzeppelin/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) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/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. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/utils/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/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/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/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _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/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/POOHEADZ.sol // POOHEADZ // CREATED BY @GERAINTTAYLOR pragma solidity ^0.8.5; pragma experimental ABIEncoderV2; contract POOHEADZ is Ownable, ERC721Enumerable, ReentrancyGuard { using SafeMath for uint256; string public POOHEAD_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN ALL ARE SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE uint256 public constant POOHEADPrice = 50000000000000000; // 0.05 ETH uint256 public constant maxPOOHEADPurchase = 10; uint256 public constant MAX_POOHEAD = 4000; bool public saleIsActive = false; mapping(uint256 => string) public POOHEADNames; // the baseURI for token metadata string public baseURI = ""; // Reserve 5 for team - Giveaways/Prizes etc uint256 public POOHEADReserve = 100; address public constant developerAddress = 0x000431DdC083C803f025C13184cdCe11fF959e64; // royalty got from a sell uint256 public constant DEVELOPER_SELL_PERCENT = 10; // 10% of sell price event licenseisLocked(string _licenseText); constructor() ERC721("PooHeadz", "POO") {} /** * @dev Withdraw contract balance to owner */ function withdraw() public onlyOwner { sendValueTo(msg.sender, address(this).balance); } /** * @dev Send an amount of value to a specific address * @param to_ address that will receive the value * @param value to be sent to the address */ function sendValueTo(address to_, uint256 value) internal { address payable to = payable(to_); (bool success, ) = to.call{value: value}(""); require(success, "Transfer failed."); } function reservePOOHEAD(address _to, uint256 _reserveAmount) public onlyOwner { uint256 supply = totalSupply(); require( _reserveAmount > 0 && _reserveAmount <= POOHEADReserve, "Not enough reserve left for team" ); for (uint256 i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } POOHEADReserve = POOHEADReserve.sub(_reserveAmount); } function setProvenanceHash(string memory provenanceHash) public onlyOwner { POOHEAD_PROVENANCE = provenanceHash; } /** * @dev baseURI for computing {tokenURI}. Empty by default, can be overwritten * in child contracts. */ function _baseURI() internal view override returns (string memory) { return baseURI; } function setBaseURI(string memory baseURI_) public onlyOwner { baseURI = baseURI_; } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } 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(uint256 _id) public view returns (string memory) { require(_id < totalSupply(), "CHOOSE A POOHEAD WITHIN RANGE"); return LICENSE_TEXT; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mintPOOHEAD(uint256 numberOfTokens) public payable nonReentrant { require(saleIsActive, "Sale must be active to mint Pooheads"); require( numberOfTokens > 0 && numberOfTokens <= maxPOOHEADPurchase, "Can only mint 10 tokens at a time" ); require( totalSupply().add(numberOfTokens) <= MAX_POOHEAD, "Purchase would exceed max supply of Pooheads" ); require( msg.value >= POOHEADPrice.mul(numberOfTokens), "Ether value sent is not correct" ); require( msg.value / numberOfTokens == POOHEADPrice, "Mint value is not good" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_POOHEAD) { _safeMint(msg.sender, mintIndex); } } uint256 value = msg.value; sendValueTo(developerAddress, (value * DEVELOPER_SELL_PERCENT) / 100); } // GET ALL OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH function POOHEADNamesOfOwner(address _owner) external view returns (string[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = POOHEADNames[ tokenOfOwnerByIndex(_owner, index) ]; } return result; } } }
IPFS URL WILL BE ADDED WHEN ALL ARE SOLD OUT
string public POOHEAD_PROVENANCE = "";
14,973,277
[ 1, 2579, 4931, 1976, 678, 15125, 9722, 11738, 7660, 29707, 8061, 432, 862, 348, 11846, 8210, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 533, 1071, 13803, 51, 12458, 67, 3373, 58, 1157, 4722, 273, 1408, 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 ]
./full_match/1/0x3F556E831FC7463aa0b716A454139f190882D477/sources/contracts/contracts/resolvers/PriceOracleResolver.sol
@notice A generelized getter for a price supplied by an oracle contract. @dev The oracle returndata must be formatted as a single uint256. @param _oracle The descriptor of our oracle e.g. ETH/USD-Maker-v1 @return The uint256 oracle price
function getPrice(string memory _oracle) external view returns (uint256) { address oracleAddr = oracle[_oracle]; if (oracleAddr == address(0)) revert("PriceOracleResolver.getPrice: no oracle"); (bool success, bytes memory returndata) = oracleAddr.staticcall( oraclePayload[_oracle] ); if (!success) returndata.revertWithError("PriceOracleResolver.getPrice:"); return abi.decode(returndata, (uint256)); }
8,465,423
[ 1, 37, 1215, 292, 1235, 7060, 364, 279, 6205, 4580, 635, 392, 20865, 6835, 18, 225, 1021, 20865, 327, 892, 1297, 506, 4955, 487, 279, 2202, 2254, 5034, 18, 225, 389, 280, 16066, 1021, 4950, 434, 3134, 20865, 425, 18, 75, 18, 512, 2455, 19, 3378, 40, 17, 12373, 17, 90, 21, 327, 1021, 2254, 5034, 20865, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 25930, 12, 1080, 3778, 389, 280, 16066, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1758, 20865, 3178, 273, 20865, 63, 67, 280, 16066, 15533, 203, 3639, 309, 261, 280, 16066, 3178, 422, 1758, 12, 20, 3719, 203, 5411, 15226, 2932, 5147, 23601, 4301, 18, 588, 5147, 30, 1158, 20865, 8863, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 20865, 3178, 18, 3845, 1991, 12, 203, 5411, 20865, 6110, 63, 67, 280, 16066, 65, 203, 3639, 11272, 203, 3639, 309, 16051, 4768, 13, 203, 5411, 327, 892, 18, 266, 1097, 25104, 2932, 5147, 23601, 4301, 18, 588, 5147, 2773, 1769, 203, 3639, 327, 24126, 18, 3922, 12, 2463, 892, 16, 261, 11890, 5034, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-27 */ // Sources flattened with hardhat v2.8.3 https://hardhat.org // File contracts/Context.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File contracts/Ownable.sol pragma solidity 0.8.9; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File contracts/ReentrancyGuard.sol pragma solidity 0.8.9; /** * @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/interfaces/IERC165.sol /** * @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 contracts/interfaces/IERC721.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; } // File contracts/interfaces/IERC721Receiver.sol /** * @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 contracts/interfaces/IERC721Metadata.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); } // File contracts/interfaces/IERC721Enumerable.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); } // File contracts/Address.sol pragma solidity 0.8.9; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/Strings.sol pragma solidity 0.8.9; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File contracts/ERC165.sol pragma solidity 0.8.9; /** * @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 contracts/ERC721A.sol pragma solidity 0.8.9; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721A: balance query for the zero address" ); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require( _exists(tokenId), "ERC721A: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721A: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File contracts/ControlledAccess.sol pragma solidity 0.8.9; /* @title ControlledAccess * @dev The ControlledAccess contract allows function to be restricted to users * that possess a signed authorization from the owner of the contract. This signed * message includes the user to give permission to and the contract address to prevent * reusing the same authorization message on different contract with same owner. */ contract ControlledAccess is Ownable { address public signerAddress; /* * @dev Requires msg.sender to have valid access message. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. */ modifier onlyValidAccess( bytes32 _r, bytes32 _s, uint8 _v ) { require(isValidAccessMessage(msg.sender, _r, _s, _v)); _; } function setSignerAddress(address newAddress) external onlyOwner { signerAddress = newAddress; } /* * @dev Verifies if message was signed by owner to give access to _add for this contract. * Assumes Geth signature prefix. * @param _add Address of agent with access * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return Validity of access message for a given address. */ function isValidAccessMessage( address _add, bytes32 _r, bytes32 _s, uint8 _v ) public view returns (bool) { bytes32 hash = keccak256(abi.encode(owner(), _add)); bytes32 message = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); address sig = ecrecover(message, _v, _r, _s); require(signerAddress == sig, "Signature does not match"); return signerAddress == sig; } } // File contracts/ASF.sol pragma solidity 0.8.9; contract ASF is ERC721A, Ownable, ReentrancyGuard, ControlledAccess { using Strings for uint256; /** Contract Functionality Variables */ uint256 public constant maxPublicMintPerAddress = 10; uint256 public constant maxPresaleMintPerAddress = 5; uint256 public constant mintPrice = 0.042 ether; uint256 public constant whitelistMintPrice = 0.0169 ether; bool public publicSaleActive = false; bool public presaleActive = false; /** URI Variables */ bytes32 public uriSuffix = ".json"; string private _baseTokenURI = ""; string public hiddenMetadataUri = "ipfs://QmVJf7dx8h9c7FPBN17LoSzRNNHjdgnvXqUG9KG3y8yT7F/hidden.json"; /** Constructor - initialize the contract by setting the name, symbol, max amount an address can mint, and the total collection size. */ constructor() ERC721A( "Alien Scum Fleet", "ASF", maxPublicMintPerAddress, 6969) { } /** Modifier - ensures the function caller is the user */ modifier callerIsUser() { require(tx.origin == msg.sender, "Caller is another contract"); _; } /** Modifier - ensures all minting requirements are met, used in both public and presale mint functions. Structure allows mintCompliance input values (_quantity, _maxPerAddress and _startTime) to be function specific */ modifier mintCompliance(uint256 _quantity, uint256 _maxPerAddress) { require(totalSupply() + _quantity <= collectionSize, "Max supply reached"); require(_quantity >= 0 && _quantity <= _maxPerAddress, "Invalid mint amount"); require(numberMinted(msg.sender) + _quantity <= _maxPerAddress, "Can not mint this many"); _; } /** Public Mint Function */ function mint(uint256 quantity) external payable callerIsUser nonReentrant mintCompliance(quantity, maxPublicMintPerAddress) /** Mint Compliance for Public Sale */ { require(publicSaleActive, "Public sale is not live."); _safeMint(msg.sender, quantity); refundIfOver(quantity * mintPrice); } /** Presale Mint Function */ function presaleMint(uint256 quantity, bytes32 _r, bytes32 _s, uint8 _v) external payable callerIsUser onlyValidAccess(_r, _s, _v) /** Whitelist */ nonReentrant mintCompliance(quantity, maxPresaleMintPerAddress) /** Mint Compliance for Presale */ { require(presaleActive, "Presale is not live."); _safeMint(msg.sender, quantity); refundIfOver(quantity * whitelistMintPrice); } /** Metadata URI */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** Total number of NFTs minted from the contract for a given address. Value can only increase and does not depend on how many NFTs are in your wallet */ function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } /** Get the owner of a specific token from the tokenId */ function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } /** Refund function which requires the minimum amount for the transaction and returns any extra payment to the sender */ function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more eth"); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } /** Standard TokenURI ERC721A function modified to return hidden metadata URI until the contract is revealed. */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "Nonexistent token!"); if (keccak256(abi.encodePacked(_baseTokenURI)) == keccak256(abi.encodePacked(""))) { return hiddenMetadataUri; } return bytes(_baseTokenURI).length > 0 ? string( abi.encodePacked(_baseTokenURI, _tokenId.toString(), uriSuffix) ) : ""; } /// OWNER FUNCTIONS /// /** Standard withdraw function for the owner to pull the contract */ function withdraw() external onlyOwner nonReentrant { uint256 sendAmount = address(this).balance; address lawi = payable(0xdC2719e36B1028Ad840B21Cd08D4F395c09A7015); address bunzo = payable(0x987F613dD3460bDCEd24Eeebfe13dE9Bf9D8d2B8); address robatic = payable(0xDd730Aa1583396214Aa2D92Cfa92880b9d93E201); address lashes = payable(0x141cA54Db6F8277917e0554b30F2B3270F65EB67); address willy = payable(0x4Bd3BB6B1D03c8844476e525fF291627FbC3c0eA); address yeti = payable(0x66c17Dcef1B364014573Ae0F869ad1c05fe01c89); address dale = payable(0x64e293dd4BBA0756895cdB8FE3a2f8E2f4AD4071); address marv = payable(0xEcf02b27e4f6Ff7E3C609652DE4B37F65A74d86B); address community = payable(0xA868Ce0B203031B2E72330e8512c8729770c0759); bool success; (success, ) = lawi.call{value: ((sendAmount * 1575) / 10000)}(""); require(success, "Transaction unsuccessful"); (success, ) = bunzo.call{value: ((sendAmount * 1575) / 10000)}(""); require(success, "Transaction unsuccessful"); (success, ) = robatic.call{value: ((sendAmount * 1575) / 10000)}(""); require(success, "Transaction unsuccessful"); (success, ) = lashes.call{value: ((sendAmount * 1575) / 10000)}(""); require(success, "Transaction unsuccessful"); (success, ) = willy.call{value: ((sendAmount * 3) / 100)}(""); require(success, "Transaction unsuccessful"); (success, ) = yeti.call{value: ((sendAmount * 12) / 100)}(""); require(success, "Transaction unsuccessful"); (success, ) = dale.call{value: ((sendAmount * 1) / 100)}(""); require(success, "Transaction unsuccessful"); (success, ) = marv.call{value: ((sendAmount * 1) / 100)}(""); require(success, "Transaction unsuccessful"); (success, ) = community.call{value: ((sendAmount * 20) / 100)}(""); require(success, "Transaction unsuccessful"); } /** Mint Function only usable by contract owner. Use reserved for giveaways and promotions. */ function ownerMint(address to, uint256 quantity) public callerIsUser onlyOwner { require(quantity + totalSupply() <= collectionSize, 'Max supply reached'); _safeMint(to, quantity); } /** Function for updating the revealed token metadata URI. When setting this value, only replace _CID_ in the following: ipfs://_CID_/ */ function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } /** Initialized in constructor - Hidden metadata value pointing to unrevealed token URI. */ function setHiddenMetadataURI(string memory _hiddenMetadataURI) public onlyOwner { hiddenMetadataUri = _hiddenMetadataURI; } function togglePresaleActive() public onlyOwner { presaleActive = !presaleActive; } function togglePublicSaleActive() public onlyOwner { publicSaleActive = !publicSaleActive; } /** adding onlyOwner and nonReentrant modifiers to ERC721A setOwnersExplicit for enhanced security */ function setOwnersExplicit(uint256 quantity) external onlyOwner nonReentrant { _setOwnersExplicit(quantity); } }
* Standard withdraw function for the owner to pull the contract */
function withdraw() external onlyOwner nonReentrant { uint256 sendAmount = address(this).balance; address lawi = payable(0xdC2719e36B1028Ad840B21Cd08D4F395c09A7015); address bunzo = payable(0x987F613dD3460bDCEd24Eeebfe13dE9Bf9D8d2B8); address robatic = payable(0xDd730Aa1583396214Aa2D92Cfa92880b9d93E201); address lashes = payable(0x141cA54Db6F8277917e0554b30F2B3270F65EB67); address willy = payable(0x4Bd3BB6B1D03c8844476e525fF291627FbC3c0eA); address yeti = payable(0x66c17Dcef1B364014573Ae0F869ad1c05fe01c89); address dale = payable(0x64e293dd4BBA0756895cdB8FE3a2f8E2f4AD4071); address marv = payable(0xEcf02b27e4f6Ff7E3C609652DE4B37F65A74d86B); address community = payable(0xA868Ce0B203031B2E72330e8512c8729770c0759); bool success; require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); require(success, "Transaction unsuccessful"); }
15,321,839
[ 1, 8336, 598, 9446, 445, 364, 326, 3410, 358, 6892, 326, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 3903, 1338, 5541, 1661, 426, 8230, 970, 288, 203, 3639, 2254, 5034, 1366, 6275, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 1758, 328, 2219, 77, 273, 8843, 429, 12, 20, 7669, 39, 5324, 3657, 73, 5718, 38, 2163, 6030, 1871, 28585, 38, 5340, 19728, 6840, 40, 24, 42, 5520, 25, 71, 5908, 37, 27, 1611, 25, 1769, 7010, 3639, 1758, 324, 318, 94, 83, 273, 8843, 429, 12, 20, 92, 10689, 27, 42, 26, 3437, 72, 40, 5026, 4848, 70, 40, 1441, 72, 3247, 41, 1340, 70, 3030, 3437, 72, 41, 29, 38, 74, 29, 40, 28, 72, 22, 38, 28, 1769, 7010, 3639, 1758, 23152, 2126, 273, 8843, 429, 12, 20, 17593, 72, 27, 5082, 37, 69, 25984, 3707, 29, 8898, 3461, 37, 69, 22, 40, 9975, 39, 507, 29, 6030, 3672, 70, 29, 72, 11180, 41, 6734, 1769, 7010, 3639, 1758, 328, 7690, 273, 8843, 429, 12, 20, 92, 3461, 21, 71, 37, 6564, 4331, 26, 42, 11149, 4700, 29, 4033, 73, 20, 2539, 24, 70, 5082, 42, 22, 38, 1578, 7301, 42, 9222, 29258, 9599, 1769, 7010, 3639, 1758, 341, 330, 715, 273, 8843, 429, 12, 20, 92, 24, 38, 72, 23, 9676, 26, 38, 21, 40, 4630, 71, 28, 5193, 6334, 6669, 73, 25, 2947, 74, 42, 5540, 2313, 5324, 42, 70, 39, 23, 71, 20, 73, 37, 1769, 7010, 3639, 1758, 4671, 77, 273, 8843, 429, 12, 20, 92, 6028, 71, 4033, 40, 311, 74, 21, 38, 23, 1105, 1611, 7950, 2 ]
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ZitCoin is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } //name this contract whatever you'd like contract ZITRON is ZitCoin { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function ZITRON( ) { balances[msg.sender] = 42069666; // Give the creator all initial tokens (100000 for example) totalSupply = 4206966642069666; // Update total supply (100000 for example) name = "ZitCoin"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "ZITRON"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
Give the creator all initial tokens (100000 for example)
balances[msg.sender] = 42069666;
10,102,405
[ 1, 43, 688, 326, 11784, 777, 2172, 2430, 261, 21, 11706, 364, 3454, 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, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 1059, 3462, 8148, 25308, 31, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x833d404fc58ea23fe8be63130bdb2d1806843517 //Contract name: Whitelist //Balance: 0 Ether //Verification Date: 2/26/2018 //Transacion Count: 413 // CODE STARTS HERE pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/Token.sol contract Token is StandardToken, Pausable { string constant public name = "Bace Token"; string constant public symbol = "BACE"; uint8 constant public decimals = 18; uint256 constant public INITIAL_TOTAL_SUPPLY = 100 * 1E6 * (uint256(10) ** (decimals)); address private addressIco; modifier onlyIco() { require(msg.sender == addressIco); _; } /** * @dev Create BACE Token contract and set pause * @param _ico The address of ICO contract. */ function Token(address _ico) public { require(_ico != address(0)); addressIco = _ico; totalSupply = totalSupply.add(INITIAL_TOTAL_SUPPLY); balances[_ico] = balances[_ico].add(INITIAL_TOTAL_SUPPLY); Transfer(address(0), _ico, INITIAL_TOTAL_SUPPLY); pause(); } /** * @dev Transfer token for a specified address with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @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) whenNotPaused public returns (bool) { super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens from ICO address to another address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) { super.transfer(_to, _value); } /** * @dev Burn remaining tokens from the ICO balance. */ function burnFromIco() onlyIco public { uint256 remainingTokens = balanceOf(addressIco); balances[addressIco] = balances[addressIco].sub(remainingTokens); totalSupply = totalSupply.sub(remainingTokens); Transfer(addressIco, address(0), remainingTokens); } /** * @dev Refund tokens from the investor balance. * @dev Function is needed for Refund investors ETH, if pre-ICO has failed. */ function refund(address _to, uint256 _value) onlyIco public { require(_value <= balances[_to]); address addr = _to; balances[addr] = balances[addr].sub(_value); balances[addressIco] = balances[addressIco].add(_value); Transfer(_to, addressIco, _value); } } // File: contracts/Whitelist.sol /** * @title Whitelist contract * @dev Whitelist for wallets. */ contract Whitelist is Ownable { mapping(address => bool) whitelist; uint256 public whitelistLength = 0; address private addressApi; modifier onlyPrivilegeAddresses { require(msg.sender == addressApi || msg.sender == owner); _; } /** * @dev Set backend Api address. * @dev Accept request from owner only. * @param _api The address of backend API. */ function setApiAddress(address _api) onlyOwner public { require(_api != address(0)); addressApi = _api; } /** * @dev Add wallet to whitelist. * @dev Accept request from the owner only. * @param _wallet The address of wallet to add. */ function addWallet(address _wallet) onlyPrivilegeAddresses public { require(_wallet != address(0)); require(!isWhitelisted(_wallet)); whitelist[_wallet] = true; whitelistLength++; } /** * @dev Remove wallet from whitelist. * @dev Accept request from the owner only. * @param _wallet The address of whitelisted wallet to remove. */ function removeWallet(address _wallet) onlyOwner public { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet] = false; whitelistLength--; } /** * @dev Check the specified wallet whether it is in the whitelist. * @param _wallet The address of wallet to check. */ function isWhitelisted(address _wallet) view public returns (bool) { return whitelist[_wallet]; } } // File: contracts/Whitelistable.sol /** * @title Whitelistable contract. * @dev Contract that can be embedded in another contract, to add functionality "whitelist". */ contract Whitelistable { Whitelist public whitelist; modifier whenWhitelisted(address _wallet) { require(whitelist.isWhitelisted(_wallet)); _; } /** * @dev Constructor for Whitelistable contract. */ function Whitelistable() public { whitelist = new Whitelist(); } } // File: contracts/Crowdsale.sol contract Crowdsale is Pausable, Whitelistable { using SafeMath for uint256; ///////////////////////////// //Constant block // // DECIMALS = 18 uint256 constant private DECIMALS = 18; // rate 1 ETH = 180 BACE tokens uint256 constant public BACE_ETH = 1800; // Bonus: 20% uint256 constant public PREICO_BONUS = 20; // 20 000 000 * 10^18 uint256 constant public RESERVED_TOKENS_BACE_TEAM = 20 * 1E6 * (10 ** DECIMALS); // 10 000 000 * 10^18 uint256 constant public RESERVED_TOKENS_ANGLE = 10 * 1E6 * (10 ** DECIMALS); // 10 000 000 * 10^18 uint256 constant public HARDCAP_TOKENS_PRE_ICO = 10 * 1E6 * (10 ** DECIMALS); // 70 000 000 * 10^18 uint256 constant public HARDCAP_TOKENS_ICO = 70 * 1E6 * (10 ** DECIMALS); // 5 000 000 * 10^18 uint256 constant public MINCAP_TOKENS = 5 * 1E6 * (10 ** DECIMALS); ///////////////////////////// ///////////////////////////// //Live cycle block // uint256 public maxInvestments; uint256 public minInvestments; /** * @dev test mode. * @dev if test mode is "true" allows to change caps in an deployed contract */ bool private testMode; /** * @dev contract BACE token object. */ Token public token; /** * @dev start time of PreIco stage. */ uint256 public preIcoStartTime; /** * @dev finish time of PreIco stage. */ uint256 public preIcoFinishTime; /** * @dev start time of Ico stage. */ uint256 public icoStartTime; /** * @dev finish time of Ico stage. */ uint256 public icoFinishTime; /** * @dev were the Ico dates set? */ bool public icoInstalled; /** * @dev The address to backend program. */ address private backendWallet; /** * @dev The address to which raised funds will be withdrawn. */ address private withdrawalWallet; /** * @dev The guard interval. */ uint256 public guardInterval; //////////////////////////// ///////////////////////////// //ETH block // /** * @dev Map of investors. Key = address, Value = Total ETH at PreIco. */ mapping(address => uint256) public preIcoInvestors; /** * @dev Array of addresses of investors at PreIco. */ address[] public preIcoInvestorsAddresses; /** * @dev Map of investors. Key = address, Value = Total ETH at Ico. */ mapping(address => uint256) public icoInvestors; /** * @dev Array of addresses of investors at Ico. */ address[] public icoInvestorsAddresses; /** * @dev Amount of investment collected in PreIco stage. (without BTC investment) */ uint256 public preIcoTotalCollected; /** * @dev Amount of investment collected in Ico stage. (without BTC investment) */ uint256 public icoTotalCollected; //////////////////////////// //////////////////////////// //Tokens block // /** * @dev Map of investors. Key = address, Value = Total tokens at PreIco. */ mapping(address => uint256) public preIcoTokenHolders; /** * @dev Array of addresses of investors. */ address[] public preIcoTokenHoldersAddresses; /** * @dev Map of investors. Key = address, Value = Total tokens at PreIco. */ mapping(address => uint256) public icoTokenHolders; /** * @dev Array of addresses of investors. */ address[] public icoTokenHoldersAddresses; /** * @dev the minimum amount in tokens for the investment. */ uint256 public minCap; /** * @dev the maximum amount in tokens for the investment in the PreIco stage. */ uint256 public hardCapPreIco; /** * @dev the maximum amount in tokens for the investment in the Ico stage. */ uint256 public hardCapIco; /** * @dev number of sold tokens issued in PreIco stage. */ uint256 public preIcoSoldTokens; /** * @dev number of sold tokens issued in Ico stage. */ uint256 public icoSoldTokens; /** * @dev The BACE token exchange rate for PreIco stage. */ uint256 public exchangeRatePreIco; /** * @dev The BACE token exchange rate for Ico stage. */ uint256 public exchangeRateIco; /** * @dev unsold BACE tokens burned?. */ bool burnt; //////////////////////////// /** * @dev Constructor for Crowdsale contract. * @dev Set the owner who can manage whitelist and token. * @param _startTimePreIco The PreIco start time. * @param _endTimePreIco The PreIco end time. * @param _angelInvestorsWallet The address to which reserved tokens angel investors will be transferred. * @param _foundersWallet The address to which reserved tokens for founders will be transferred. * @param _backendWallet The address to backend program. * @param _withdrawalWallet The address to which raised funds will be withdrawn. * @param _testMode test mode is on? */ function Crowdsale ( uint256 _startTimePreIco, uint256 _endTimePreIco, address _angelInvestorsWallet, address _foundersWallet, address _backendWallet, address _withdrawalWallet, uint256 _maxInvestments, uint256 _minInvestments, bool _testMode ) public Whitelistable() { require(_angelInvestorsWallet != address(0) && _foundersWallet != address(0) && _backendWallet != address(0) && _withdrawalWallet != address(0)); require(_startTimePreIco >= now && _endTimePreIco > _startTimePreIco); require(_maxInvestments != 0 && _minInvestments != 0 && _maxInvestments > _minInvestments); //////////////////////////// //Live cycle block init // testMode = _testMode; token = new Token(this); maxInvestments = _maxInvestments; minInvestments = _minInvestments; preIcoStartTime = _startTimePreIco; preIcoFinishTime = _endTimePreIco; icoStartTime = 0; icoFinishTime = 0; icoInstalled = false; guardInterval = uint256(86400).mul(7); //guard interval - 1 week ///////////////////////////// //////////////////////////// //ETH block init preIcoTotalCollected = 0; icoTotalCollected = 0; ///////////////////////////// //////////////////////////// //Tokens block init // minCap = MINCAP_TOKENS; hardCapPreIco = HARDCAP_TOKENS_PRE_ICO; hardCapIco = HARDCAP_TOKENS_ICO; preIcoSoldTokens = 0; icoSoldTokens = 0; exchangeRateIco = BACE_ETH; exchangeRatePreIco = exchangeRateIco.mul(uint256(100).add(PREICO_BONUS)).div(100); burnt = false; //////////////////////////// backendWallet = _backendWallet; withdrawalWallet = _withdrawalWallet; whitelist.transferOwnership(msg.sender); token.transferFromIco(_angelInvestorsWallet, RESERVED_TOKENS_ANGLE); token.transferFromIco(_foundersWallet, RESERVED_TOKENS_BACE_TEAM); token.transferOwnership(msg.sender); } modifier isTestMode() { require(testMode); _; } /** * @dev check Ico Failed. * @return bool true if Ico Failed. */ function isIcoFailed() public view returns (bool) { return isIcoFinish() && icoSoldTokens.add(preIcoSoldTokens) < minCap; } /** * @dev check Ico Success. * @return bool true if Ico Success. */ function isIcoSuccess() public view returns (bool) { return isIcoFinish() && icoSoldTokens.add(preIcoSoldTokens) >= minCap; } /** * @dev check PreIco Stage. * @return bool true if PreIco Stage now. */ function isPreIcoStage() public view returns (bool) { return now > preIcoStartTime && now < preIcoFinishTime; } /** * @dev check Ico Stage. * @return bool true if Ico Stage now. */ function isIcoStage() public view returns (bool) { return icoInstalled && now > icoStartTime && now < icoFinishTime; } /** * @dev check PreIco Finish. * @return bool true if PreIco Finished. */ function isPreIcoFinish() public view returns (bool) { return now > preIcoFinishTime; } /** * @dev check Ico Finish. * @return bool true if Ico Finished. */ function isIcoFinish() public view returns (bool) { return icoInstalled && now > icoFinishTime; } /** * @dev guard interval finished? * @return bool true if guard Interval finished. */ function guardIntervalFinished() public view returns (bool) { return now > icoFinishTime.add(guardInterval); } /** * @dev Set start time and end time for Ico. * @param _startTimeIco The Ico start time. * @param _endTimeIco The Ico end time. */ function setStartTimeIco(uint256 _startTimeIco, uint256 _endTimeIco) onlyOwner public { require(_startTimeIco >= now && _endTimeIco > _startTimeIco && _startTimeIco > preIcoFinishTime); icoStartTime = _startTimeIco; icoFinishTime = _endTimeIco; icoInstalled = true; } /** * @dev Remaining amount of tokens for PreIco stage. */ function tokensRemainingPreIco() public view returns(uint256) { if (isPreIcoFinish()) { return 0; } return hardCapPreIco.sub(preIcoSoldTokens); } /** * @dev Remaining amount of tokens for Ico stage. */ function tokensRemainingIco() public view returns(uint256) { if (burnt) { return 0; } if (isPreIcoFinish()) { return hardCapIco.sub(icoSoldTokens).sub(preIcoSoldTokens); } return hardCapIco.sub(hardCapPreIco).sub(icoSoldTokens); } /** * @dev Add information about the investment at the PreIco stage. * @param _addr Investor's address. * @param _weis Amount of wei(1 ETH = 1 * 10 ** 18 wei) received. * @param _tokens Amount of Token for investor. */ function addInvestInfoPreIco(address _addr, uint256 _weis, uint256 _tokens) private { if (preIcoTokenHolders[_addr] == 0) { preIcoTokenHoldersAddresses.push(_addr); } preIcoTokenHolders[_addr] = preIcoTokenHolders[_addr].add(_tokens); preIcoSoldTokens = preIcoSoldTokens.add(_tokens); if (_weis > 0) { if (preIcoInvestors[_addr] == 0) { preIcoInvestorsAddresses.push(_addr); } preIcoInvestors[_addr] = preIcoInvestors[_addr].add(_weis); preIcoTotalCollected = preIcoTotalCollected.add(_weis); } } /** * @dev Add information about the investment at the Ico stage. * @param _addr Investor's address. * @param _weis Amount of wei(1 ETH = 1 * 10 ** 18 wei) received. * @param _tokens Amount of Token for investor. */ function addInvestInfoIco(address _addr, uint256 _weis, uint256 _tokens) private { if (icoTokenHolders[_addr] == 0) { icoTokenHoldersAddresses.push(_addr); } icoTokenHolders[_addr] = icoTokenHolders[_addr].add(_tokens); icoSoldTokens = icoSoldTokens.add(_tokens); if (_weis > 0) { if (icoInvestors[_addr] == 0) { icoInvestorsAddresses.push(_addr); } icoInvestors[_addr] = icoInvestors[_addr].add(_weis); icoTotalCollected = icoTotalCollected.add(_weis); } } /** * @dev Fallback function can be used to buy tokens. */ function() public payable { acceptInvestments(msg.sender, msg.value); } /** * @dev function can be used to buy tokens by ETH investors. */ function sellTokens() public payable { acceptInvestments(msg.sender, msg.value); } /** * @dev Function processing new investments. * @param _addr Investor's address. * @param _amount The amount of wei(1 ETH = 1 * 10 ** 18 wei) received. */ function acceptInvestments(address _addr, uint256 _amount) private whenWhitelisted(msg.sender) whenNotPaused { require(_addr != address(0) && _amount >= minInvestments); bool preIco = isPreIcoStage(); bool ico = isIcoStage(); require(preIco || ico); require((preIco && tokensRemainingPreIco() > 0) || (ico && tokensRemainingIco() > 0)); uint256 intermediateEthInvestment; uint256 ethSurrender = 0; uint256 currentEth = preIco ? preIcoInvestors[_addr] : icoInvestors[_addr]; if (currentEth.add(_amount) > maxInvestments) { intermediateEthInvestment = maxInvestments.sub(currentEth); ethSurrender = ethSurrender.add(_amount.sub(intermediateEthInvestment)); } else { intermediateEthInvestment = _amount; } uint256 currentRate = preIco ? exchangeRatePreIco : exchangeRateIco; uint256 intermediateTokenInvestment = intermediateEthInvestment.mul(currentRate); uint256 tokensRemaining = preIco ? tokensRemainingPreIco() : tokensRemainingIco(); uint256 currentTokens = preIco ? preIcoTokenHolders[_addr] : icoTokenHolders[_addr]; uint256 weiToAccept; uint256 tokensToSell; if (currentTokens.add(intermediateTokenInvestment) > tokensRemaining) { tokensToSell = tokensRemaining; weiToAccept = tokensToSell.div(currentRate); ethSurrender = ethSurrender.add(intermediateEthInvestment.sub(weiToAccept)); } else { tokensToSell = intermediateTokenInvestment; weiToAccept = intermediateEthInvestment; } if (preIco) { addInvestInfoPreIco(_addr, weiToAccept, tokensToSell); } else { addInvestInfoIco(_addr, weiToAccept, tokensToSell); } token.transferFromIco(_addr, tokensToSell); if (ethSurrender > 0) { msg.sender.transfer(ethSurrender); } } /** * @dev Function can be used to buy tokens by third-party investors. * @dev Only the owner or the backend can call this function. * @param _addr Investor's address. * @param _value Amount of Token for investor. */ function thirdPartyInvestments(address _addr, uint256 _value) public whenWhitelisted(_addr) whenNotPaused { require(msg.sender == backendWallet || msg.sender == owner); require(_addr != address(0) && _value > 0); bool preIco = isPreIcoStage(); bool ico = isIcoStage(); require(preIco || ico); require((preIco && tokensRemainingPreIco() > 0) || (ico && tokensRemainingIco() > 0)); uint256 currentRate = preIco ? exchangeRatePreIco : exchangeRateIco; uint256 currentTokens = preIco ? preIcoTokenHolders[_addr] : icoTokenHolders[_addr]; require(maxInvestments.mul(currentRate) >= currentTokens.add(_value)); require(minInvestments.mul(currentRate) <= _value); uint256 tokensRemaining = preIco ? tokensRemainingPreIco() : tokensRemainingIco(); require(tokensRemaining >= _value); if (preIco) { addInvestInfoPreIco(_addr, 0, _value); } else { addInvestInfoIco(_addr, 0, _value); } token.transferFromIco(_addr, _value); } /** * @dev Send raised funds to the withdrawal wallet. * @param _weiAmount The amount of raised funds to withdraw. */ function forwardFunds(uint256 _weiAmount) public onlyOwner { require(isIcoSuccess() || (isIcoFailed() && guardIntervalFinished())); withdrawalWallet.transfer(_weiAmount); } /** * @dev Function for refund eth if Ico failed and guard interval has not expired. * @dev Any wallet can call the function. * @dev Function returns ETH for sender if it is a member of Ico or(and) PreIco. */ function refund() public { require(isIcoFailed() && !guardIntervalFinished()); uint256 ethAmountPreIco = preIcoInvestors[msg.sender]; uint256 ethAmountIco = icoInvestors[msg.sender]; uint256 ethAmount = ethAmountIco.add(ethAmountPreIco); uint256 tokensAmountPreIco = preIcoTokenHolders[msg.sender]; uint256 tokensAmountIco = icoTokenHolders[msg.sender]; uint256 tokensAmount = tokensAmountPreIco.add(tokensAmountIco); require(ethAmount > 0 && tokensAmount > 0); preIcoInvestors[msg.sender] = 0; icoInvestors[msg.sender] = 0; preIcoTokenHolders[msg.sender] = 0; icoTokenHolders[msg.sender] = 0; msg.sender.transfer(ethAmount); token.refund(msg.sender, tokensAmount); } /** * @dev Set new withdrawal wallet address. * @param _addr new withdrawal Wallet address. */ function setWithdrawalWallet(address _addr) public onlyOwner { require(_addr != address(0)); withdrawalWallet = _addr; } /** * @dev Set new backend wallet address. * @param _addr new backend Wallet address. */ function setBackendWallet(address _addr) public onlyOwner { require(_addr != address(0)); backendWallet = _addr; } /** * @dev Burn unsold tokens from the Ico balance. * @dev Only applies when the Ico was ended. */ function burnUnsoldTokens() onlyOwner public { require(isIcoFinish()); token.burnFromIco(); burnt = true; } /** * @dev Set new MinCap. * @param _newMinCap new MinCap, */ function setMinCap(uint256 _newMinCap) public onlyOwner isTestMode { require(now < preIcoFinishTime); minCap = _newMinCap; } /** * @dev Set new PreIco HardCap. * @param _newPreIcoHardCap new PreIco HardCap, */ function setPreIcoHardCap(uint256 _newPreIcoHardCap) public onlyOwner isTestMode { require(now < preIcoFinishTime); require(_newPreIcoHardCap <= hardCapIco); hardCapPreIco = _newPreIcoHardCap; } /** * @dev Set new Ico HardCap. * @param _newIcoHardCap new Ico HardCap, */ function setIcoHardCap(uint256 _newIcoHardCap) public onlyOwner isTestMode { require(now < preIcoFinishTime); require(_newIcoHardCap > hardCapPreIco); hardCapIco = _newIcoHardCap; } /** * @dev Count the Ico investors total. */ function getIcoTokenHoldersAddressesCount() public view returns(uint256) { return icoTokenHoldersAddresses.length; } /** * @dev Count the PreIco investors total. */ function getPreIcoTokenHoldersAddressesCount() public view returns(uint256) { return preIcoTokenHoldersAddresses.length; } /** * @dev Count the Ico investors total (not including third-party investors). */ function getIcoInvestorsAddressesCount() public view returns(uint256) { return icoInvestorsAddresses.length; } /** * @dev Count the PreIco investors total (not including third-party investors). */ function getPreIcoInvestorsAddressesCount() public view returns(uint256) { return preIcoInvestorsAddresses.length; } /** * @dev Get backend wallet address. */ function getBackendWallet() public view returns(address) { return backendWallet; } /** * @dev Get Withdrawal wallet address. */ function getWithdrawalWallet() public view returns(address) { return withdrawalWallet; } } // File: contracts/CrowdsaleFactory.sol contract Factory { Crowdsale public crowdsale; function createCrowdsale ( uint256 _startTimePreIco, uint256 _endTimePreIco, address _angelInvestorsWallet, address _foundersWallet, address _backendWallet, address _withdrawalWallet, uint256 _maxInvestments, uint256 _minInvestments, bool _testMode ) public { crowdsale = new Crowdsale( _startTimePreIco, _endTimePreIco, _angelInvestorsWallet, _foundersWallet, _backendWallet, _withdrawalWallet, _maxInvestments, _minInvestments, _testMode ); Whitelist whitelist = crowdsale.whitelist(); whitelist.transferOwnership(msg.sender); Token token = crowdsale.token(); token.transferOwnership(msg.sender); crowdsale.transferOwnership(msg.sender); } }
* @dev Set start time and end time for Ico. @param _startTimeIco The Ico start time. @param _endTimeIco The Ico end time./
function setStartTimeIco(uint256 _startTimeIco, uint256 _endTimeIco) onlyOwner public { require(_startTimeIco >= now && _endTimeIco > _startTimeIco && _startTimeIco > preIcoFinishTime); icoStartTime = _startTimeIco; icoFinishTime = _endTimeIco; icoInstalled = true; }
5,346,386
[ 1, 694, 787, 813, 471, 679, 813, 364, 467, 2894, 18, 225, 389, 1937, 950, 45, 2894, 1021, 467, 2894, 787, 813, 18, 225, 389, 409, 950, 45, 2894, 1021, 467, 2894, 679, 813, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 13649, 45, 2894, 12, 11890, 5034, 389, 1937, 950, 45, 2894, 16, 2254, 5034, 389, 409, 950, 45, 2894, 13, 1338, 5541, 1071, 288, 203, 3639, 2583, 24899, 1937, 950, 45, 2894, 1545, 2037, 597, 389, 409, 950, 45, 2894, 405, 389, 1937, 950, 45, 2894, 597, 389, 1937, 950, 45, 2894, 405, 675, 45, 2894, 11641, 950, 1769, 203, 203, 3639, 277, 2894, 13649, 273, 389, 1937, 950, 45, 2894, 31, 203, 3639, 277, 2894, 11641, 950, 273, 389, 409, 950, 45, 2894, 31, 203, 3639, 277, 2894, 16747, 273, 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 ]
//! The Secret Store document key shadow retrieval service contract. //! //! Copyright 2017 Svyatoslav Nikolsky, Parity Technologies Ltd. //! //! 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.99 <0.6.0; import "./SecretStoreService.sol"; import "./SecretStoreServiceBase.sol"; /// Document Key shadow retrieval service contract. /* solium-disable-next-line */ contract SecretStoreDocumentKeyShadowRetrievalService is SecretStoreServiceBase, DocumentKeyShadowRetrievalServiceClientApi, DocumentKeyShadowRetrievalServiceKeyServerApi { /// Document key shadow retrieval request. struct DocumentKeyShadowRetrievalRequest { // public portion-related data bytes32 serverKeyId; bytes requesterPublic; RequestResponses commonRetrievalResponses; bool isCommonRetrievalCompleted; uint8 threshold; // personal portion-related data uint256 personalRetrievalErrors; uint8 personalRetrievalErrorsCount; bytes32[] personalDataKeys; mapping (bytes32 => DocumentKeyShadowRetrievalData) personalData; } /// Document key retrieval data. struct DocumentKeyShadowRetrievalData { uint256 participants; uint256 reported; uint8 reportedCount; } //// Only pass when caller is the owner of given public key. modifier onlyPublicOwner(bytes memory publicKey) { require(address(uint(keccak256(publicKey)) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) == msg.sender, "Only public owner"); _; } /// When document key common-portion retrieval request is received. event DocumentKeyCommonRetrievalRequested(bytes32 serverKeyId, address requester); /// When document key personal-portion retrieval request is received. event DocumentKeyPersonalRetrievalRequested(bytes32 serverKeyId, bytes requesterPublic); /// When document key common portion is retrieved. Ater this event s fired, wait for /// exactly `threshold+1` `DocumentKeyPersonalRetrieved` events with the same `decryptedSecret` value. event DocumentKeyCommonRetrieved(bytes32 indexed serverKeyId, address indexed requester, bytes commonPoint, uint8 threshold); /// When document key personal portion is retrieved. After enough events are fired, use `secretstore_shadowDecrypt` /// to decrypt document contents. event DocumentKeyPersonalRetrieved(bytes32 indexed serverKeyId, address indexed requester, bytes decryptedSecret, bytes shadow); /// When error occurs during document key retrieval. event DocumentKeyShadowRetrievalError(bytes32 indexed serverKeyId, address indexed requester); /// Constructor. constructor(address keyServerSetAddressInit) SecretStoreServiceBase(keyServerSetAddressInit) public { documentKeyShadowRetrievalFee = 200 finney; maxDocumentKeyShadowRetrievalRequests = 4; } // === Interface methods === /// We do not support direct payments. function() external payable { revert("Direct payment not supported"); } /// Request document key retrieval. function retrieveDocumentKeyShadow(bytes32 serverKeyId, bytes calldata requesterPublic) external payable whenFeePaid(documentKeyShadowRetrievalFee) validPublic(requesterPublic) onlyPublicOwner(requesterPublic) { // check maximum number of requests require(documentKeyShadowRetrievalRequestsKeys.length < maxDocumentKeyShadowRetrievalRequests, "Should less than max"); bytes32 retrievalId = keccak256(abi.encodePacked(serverKeyId, msg.sender)); DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; require(request.requesterPublic.length == 0, "Should empty"); deposit(); // we do not know exact threshold value here && we can not blindly trust the first response // => we should agree upon two values: threshold && document key itself // => assuming that all authorities will eventually respond with value/error, we will wait for: // 1) at least 50% + 1 authorities agreement on the same threshold value // 2) after threshold is agreed, we will wait for threshold + 1 values of document key // the data required to compute document key is the triple { commonPoint, encryptedPoint, shadowPoints[] } // this data is computed on threshold + 1 nodes only // retrieval consists of two phases: // 1) every authority that is seeing retrieval request, publishes { commonPoint, encryptedPoint, threshold } // 2) master node starts decryption session // 2.1) every node participating in decryption session publishes { address[], shadow } // 2.2) once there are threshold + 1 confirmations of { address[], shadow } from exactly address[] authorities, we are publishing the key request.serverKeyId = serverKeyId; request.requesterPublic = requesterPublic; documentKeyShadowRetrievalRequestsKeys.push(retrievalId); emit DocumentKeyCommonRetrievalRequested(serverKeyId, msg.sender); } /// Called when common data is reported by key server. function documentKeyCommonRetrieved( bytes32 serverKeyId, address requester, bytes calldata commonPoint, uint8 threshold) external validPublic(commonPoint) { // check if request still active bytes32 retrievalId = keccak256(abi.encodePacked(serverKeyId, requester)); DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; if (request.isCommonRetrievalCompleted || request.requesterPublic.length == 0) { return; } // insert response uint8 keyServerIndex = requireKeyServer(msg.sender); bytes32 commonResponse = keccak256(abi.encodePacked(commonPoint, threshold)); ResponseSupport commonResponseSupport = insertResponse( request.commonRetrievalResponses, keyServerIndex, keyServersCount() / 2, commonResponse); // ...and check if there are enough support if (commonResponseSupport == ResponseSupport.Unconfirmed) { // not confirmed (yet) return; } // if common consensus isn't possible => personal retrieval is also impossible if (commonResponseSupport == ResponseSupport.Impossible) { clearDocumentKeyShadowRetrievalRequest(retrievalId, request); emit DocumentKeyShadowRetrievalError(serverKeyId, requester); return; } // else => remember required data request.isCommonRetrievalCompleted = true; request.threshold = threshold; // ...and publish common data (this is also a signal to 'master' key server to start decryption) emit DocumentKeyCommonRetrieved( serverKeyId, requester, commonPoint, threshold); emit DocumentKeyPersonalRetrievalRequested(serverKeyId, request.requesterPublic); } /// Called when 'personal' data is reported by key server. function documentKeyPersonalRetrieved( bytes32 serverKeyId, address requester, uint256 participants, bytes calldata decryptedSecret, bytes calldata shadow) external validPublic(decryptedSecret) { // check if request still active bytes32 retrievalId = keccak256(abi.encodePacked(serverKeyId, requester)); DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; if (request.requesterPublic.length == 0) { return; } // we do not accept personal data until common is retrieved require(request.isCommonRetrievalCompleted, "Should not completed yet"); // there must be exactly threshold + 1 participated key servers // TODO: require(request.threshold + 1 == participants.length); // key server must have an entry in participants uint8 keyServerIndex = requireKeyServer(msg.sender); uint256 keyServerMask = (uint256(1) << keyServerIndex); require((participants & keyServerMask) != 0, "Both should not null"); // insert new personal data bytes32 personalDataId = keccak256(abi.encodePacked(participants, decryptedSecret)); DocumentKeyShadowRetrievalData storage personalData = request.personalData[personalDataId]; if (personalData.participants == 0) { request.personalDataKeys.push(personalDataId); personalData.participants = participants; } else { require((personalData.reported & keyServerMask) == 0, "Should not reported"); } // remember result personalData.reportedCount += 1; personalData.reported |= keyServerMask; // publish personal portion emit DocumentKeyPersonalRetrieved( serverKeyId, requester, decryptedSecret, shadow); // check if all participants have responded if (request.threshold != personalData.reportedCount - 1) { return; } // delete request clearDocumentKeyShadowRetrievalRequest(retrievalId, request); } /// Called when error occurs during document key shadow retrieval. function documentKeyShadowRetrievalError(bytes32 serverKeyId, address requester) external { // check if request still active bytes32 retrievalId = keccak256(abi.encodePacked(serverKeyId, requester)); DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; if (request.requesterPublic.length == 0) { return; } // error on common data retrieval step is treated like a voting for non-existant common data uint8 keyServerIndex = requireKeyServer(msg.sender); if (!request.isCommonRetrievalCompleted) { // insert response bytes32 invalidResponse = bytes32(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); ResponseSupport invalidResponseSupport = insertResponse( request.commonRetrievalResponses, keyServerIndex, keyServersCount() / 2, invalidResponse); // ...and check if there are enough confirmations for invalid response if (invalidResponseSupport == ResponseSupport.Unconfirmed) { return; } // delete request and fire event clearDocumentKeyShadowRetrievalRequest(retrievalId, request); emit DocumentKeyShadowRetrievalError(serverKeyId, requester); return; } // else error has occured during personal data retrieval // this could be: // 1) access denied error (because KS is out of sync?) // 2) key has became irrecoverable // 3) key server is cheating // there's currently no strong criteria - when to stop retrying to serve request // stopping it after first error isn't good, because this means that any KS can reject request // waiting for N errors isn't good, because consensus set in decryption session is constructed // right after t+1 nodes have responded with AGREE => some of nodes (with bad connectivity) might be // 'banned' from this session forever // waiting for any threshold-related errors count will fail if this count is larger than N // => let's wait for N/2+1 errors from different nodes uint256 keyServerMask = uint256(1) << keyServerIndex; if ((request.personalRetrievalErrors & keyServerMask) != 0) { return; } request.personalRetrievalErrors |= keyServerMask; request.personalRetrievalErrorsCount += 1; // check if we have enough errors if (request.personalRetrievalErrorsCount < keyServersCount() / 2 + 1) { return; } // delete request and fire event clearDocumentKeyShadowRetrievalRequest(retrievalId, request); emit DocumentKeyShadowRetrievalError(serverKeyId, requester); } /// Get count of pending document key shadow retrieval requests. function documentKeyShadowRetrievalRequestsCount() external view returns (uint256) { return documentKeyShadowRetrievalRequestsKeys.length; } /// Get document key shadow retrieval request with given index. /// Returns: (serverKeyId, requesterPublic, isCommonRetrievalCompleted) function getDocumentKeyShadowRetrievalRequest(uint256 index) external view returns (bytes32, bytes memory, bool) { bytes32 retrievalId = documentKeyShadowRetrievalRequestsKeys[index]; DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; return ( request.serverKeyId, request.requesterPublic, request.isCommonRetrievalCompleted ); } /// Returs true if response from given keyServer is required. function isDocumentKeyShadowRetrievalResponseRequired(bytes32 serverKeyId, address requester, address keyServer) external view returns (bool) { uint8 keyServerIndex = requireKeyServer(keyServer); bytes32 retrievalId = keccak256(abi.encodePacked(serverKeyId, requester)); DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; // response is always required when personal retrieval is requested return request.isCommonRetrievalCompleted || isResponseRequired(request.commonRetrievalResponses, keyServerIndex); } // === Administrative methods === /// Set document key shadow retrieval fee. function setDocumentKeyShadowRetrievalFee(uint256 newFee) public onlyOwner { documentKeyShadowRetrievalFee = newFee; } /// Set document key shadow retrieval requests limit. function setMaxDocumentKeyShadowRetrievalRequests(uint256 newLimit) public onlyOwner { maxDocumentKeyShadowRetrievalRequests = newLimit; } /// Delete document key shadow retrieval request. function deleteDocumentKeyShadowRetrievalRequest(bytes32 serverKeyId, address requester) public onlyOwner { bytes32 retrievalId = keccak256(abi.encodePacked(serverKeyId, requester)); DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; clearDocumentKeyShadowRetrievalRequest(retrievalId, request); emit DocumentKeyShadowRetrievalError(serverKeyId, requester); } // === Internal methods === /// Clear document key shadow retrieval request traces. function clearDocumentKeyShadowRetrievalRequest(bytes32 retrievalId, DocumentKeyShadowRetrievalRequest storage request) private { for (uint i = 0; i < request.personalDataKeys.length; ++i) { delete request.personalData[request.personalDataKeys[i]]; } clearResponses(request.commonRetrievalResponses); delete documentKeyShadowRetrievalRequests[retrievalId]; removeRequestKey(documentKeyShadowRetrievalRequestsKeys, retrievalId); } /// Document key shadow retrieval fee. uint256 public documentKeyShadowRetrievalFee; /// Maximal number of active document key shadow retrieval requests. We're limiting this number to avoid /// infinite gas costs of some functions. uint256 public maxDocumentKeyShadowRetrievalRequests; /// Pending store requests. mapping (bytes32 => DocumentKeyShadowRetrievalRequest) private documentKeyShadowRetrievalRequests; /// Pending store requests keys. bytes32[] private documentKeyShadowRetrievalRequestsKeys; }
Called when error occurs during document key shadow retrieval. check if request still active
function documentKeyShadowRetrievalError(bytes32 serverKeyId, address requester) external { bytes32 retrievalId = keccak256(abi.encodePacked(serverKeyId, requester)); DocumentKeyShadowRetrievalRequest storage request = documentKeyShadowRetrievalRequests[retrievalId]; if (request.requesterPublic.length == 0) { return; } uint8 keyServerIndex = requireKeyServer(msg.sender); if (!request.isCommonRetrievalCompleted) { bytes32 invalidResponse = bytes32(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); ResponseSupport invalidResponseSupport = insertResponse( request.commonRetrievalResponses, keyServerIndex, keyServersCount() / 2, invalidResponse); if (invalidResponseSupport == ResponseSupport.Unconfirmed) { return; } emit DocumentKeyShadowRetrievalError(serverKeyId, requester); return; } if (!request.isCommonRetrievalCompleted) { bytes32 invalidResponse = bytes32(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); ResponseSupport invalidResponseSupport = insertResponse( request.commonRetrievalResponses, keyServerIndex, keyServersCount() / 2, invalidResponse); if (invalidResponseSupport == ResponseSupport.Unconfirmed) { return; } emit DocumentKeyShadowRetrievalError(serverKeyId, requester); return; } clearDocumentKeyShadowRetrievalRequest(retrievalId, request); uint256 keyServerMask = uint256(1) << keyServerIndex; if ((request.personalRetrievalErrors & keyServerMask) != 0) { return; } request.personalRetrievalErrors |= keyServerMask; request.personalRetrievalErrorsCount += 1; if (request.personalRetrievalErrorsCount < keyServersCount() / 2 + 1) { return; } emit DocumentKeyShadowRetrievalError(serverKeyId, requester); clearDocumentKeyShadowRetrievalRequest(retrievalId, request); }
1,000,768
[ 1, 8185, 1347, 555, 9938, 4982, 1668, 498, 10510, 22613, 18, 866, 309, 590, 4859, 2695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 1668, 653, 12957, 27356, 668, 12, 3890, 1578, 1438, 14140, 16, 1758, 19961, 13, 3903, 288, 203, 202, 202, 3890, 1578, 22613, 548, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3567, 14140, 16, 19961, 10019, 203, 202, 202, 2519, 653, 12957, 27356, 691, 2502, 590, 273, 1668, 653, 12957, 27356, 6421, 63, 14580, 1125, 548, 15533, 203, 202, 202, 430, 261, 2293, 18, 26192, 4782, 18, 2469, 422, 374, 13, 288, 203, 1082, 202, 2463, 31, 203, 202, 202, 97, 203, 203, 202, 202, 11890, 28, 498, 2081, 1016, 273, 2583, 653, 2081, 12, 3576, 18, 15330, 1769, 203, 202, 202, 430, 16051, 2293, 18, 291, 6517, 27356, 9556, 13, 288, 203, 1082, 202, 3890, 1578, 2057, 1064, 273, 1731, 1578, 12, 20, 6356, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 18343, 1769, 203, 1082, 202, 1064, 6289, 2057, 1064, 6289, 273, 2243, 1064, 12, 203, 9506, 202, 2293, 18, 6054, 27356, 12222, 16, 203, 9506, 202, 856, 2081, 1016, 16, 203, 9506, 202, 856, 11913, 1380, 1435, 342, 576, 16, 203, 9506, 202, 5387, 1064, 1769, 203, 203, 1082, 202, 430, 261, 5387, 1064, 6289, 422, 2306, 6289, 18, 984, 21606, 13, 288, 203, 9506, 202, 2463, 31, 203, 1082, 202, 97, 203, 203, 1082, 202, 18356, 4319, 653, 12957, 27356, 668, 12, 3567, 14140, 16, 19961, 1769, 203, 1082, 202, 2463, 31, 203, 202, 202, 97, 203, 203, 202, 202, 430, 16051, 2293, 18, 291, 6517, 27356, 9556, 2 ]
pragma solidity ^0.4.13; interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() public view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); } interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract LicenseAccessControl { /** * @notice ContractUpgrade is the event that will be emitted if we set a new contract address */ event ContractUpgrade(address newContract); event Paused(); event Unpaused(); /** * @notice CEO's address FOOBAR */ address public ceoAddress; /** * @notice CFO's address */ address public cfoAddress; /** * @notice COO's address */ address public cooAddress; /** * @notice withdrawal address */ address public withdrawalAddress; bool public paused = false; /** * @dev Modifier to make a function only callable by the CEO */ modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /** * @dev Modifier to make a function only callable by the CFO */ modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /** * @dev Modifier to make a function only callable by the COO */ modifier onlyCOO() { require(msg.sender == cooAddress); _; } /** * @dev Modifier to make a function only callable by C-level execs */ modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or CFO */ modifier onlyCEOOrCFO() { require( msg.sender == cfoAddress || msg.sender == ceoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or COO */ modifier onlyCEOOrCOO() { require( msg.sender == cooAddress || msg.sender == ceoAddress ); _; } /** * @notice Sets a new CEO * @param _newCEO - the address of the new CEO */ function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /** * @notice Sets a new CFO * @param _newCFO - the address of the new CFO */ function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /** * @notice Sets a new COO * @param _newCOO - the address of the new COO */ function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /** * @notice Sets a new withdrawalAddress * @param _newWithdrawalAddress - the address where we'll send the funds */ function setWithdrawalAddress(address _newWithdrawalAddress) external onlyCEO { require(_newWithdrawalAddress != address(0)); withdrawalAddress = _newWithdrawalAddress; } /** * @notice Withdraw the balance to the withdrawalAddress * @dev We set a withdrawal address seperate from the CFO because this allows us to withdraw to a cold wallet. */ function withdrawBalance() external onlyCEOOrCFO { require(withdrawalAddress != address(0)); withdrawalAddress.transfer(this.balance); } /** Pausable functionality adapted from OpenZeppelin **/ /** * @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); _; } /** * @notice called by any C-level to pause, triggers stopped state */ function pause() public onlyCLevel whenNotPaused { paused = true; Paused(); } /** * @notice called by the CEO to unpause, returns to normal state */ function unpause() public onlyCEO whenPaused { paused = false; Unpaused(); } } contract LicenseBase is LicenseAccessControl { /** * @notice Issued is emitted when a new license is issued */ event LicenseIssued( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 attributes, uint256 issuedTime, uint256 expirationTime, address affiliate ); event LicenseRenewal( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 expirationTime ); struct License { uint256 productId; uint256 attributes; uint256 issuedTime; uint256 expirationTime; address affiliate; } /** * @notice All licenses in existence. * @dev The ID of each license is an index in this array. */ License[] licenses; /** internal **/ function _isValidLicense(uint256 _licenseId) internal view returns (bool) { return licenseProductId(_licenseId) != 0; } /** anyone **/ /** * @notice Get a license's productId * @param _licenseId the license id */ function licenseProductId(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].productId; } /** * @notice Get a license's attributes * @param _licenseId the license id */ function licenseAttributes(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].attributes; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseIssuedTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].issuedTime; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseExpirationTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].expirationTime; } /** * @notice Get a the affiliate credited for the sale of this license * @param _licenseId the license id */ function licenseAffiliate(uint256 _licenseId) public view returns (address) { return licenses[_licenseId].affiliate; } /** * @notice Get a license's info * @param _licenseId the license id */ function licenseInfo(uint256 _licenseId) public view returns (uint256, uint256, uint256, uint256, address) { return ( licenseProductId(_licenseId), licenseAttributes(_licenseId), licenseIssuedTime(_licenseId), licenseExpirationTime(_licenseId), licenseAffiliate(_licenseId) ); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract AffiliateProgram is Pausable { using SafeMath for uint256; event AffiliateCredit( // The address of the affiliate address affiliate, // The store's ID of what was sold (e.g. a tokenId) uint256 productId, // The amount owed this affiliate in this sale uint256 amount ); event Withdraw(address affiliate, address to, uint256 amount); event Whitelisted(address affiliate, uint256 amount); event RateChanged(uint256 rate, uint256 amount); // @notice A mapping from affiliate address to their balance mapping (address => uint256) public balances; // @notice A mapping from affiliate address to the time of last deposit mapping (address => uint256) public lastDepositTimes; // @notice The last deposit globally uint256 public lastDepositTime; // @notice The maximum rate for any affiliate // @dev The hard-coded maximum affiliate rate (in basis points) // All rates are measured in basis points (1/100 of a percent) // Values 0-10,000 map to 0%-100% uint256 private constant hardCodedMaximumRate = 5000; // @notice The commission exiration time // @dev Affiliate commissions expire if they are unclaimed after this amount of time uint256 private constant commissionExpiryTime = 30 days; // @notice The baseline affiliate rate (in basis points) for non-whitelisted referrals uint256 public baselineRate = 0; // @notice A mapping from whitelisted referrals to their individual rates mapping (address => uint256) public whitelistRates; // @notice The maximum rate for any affiliate // @dev overrides individual rates. This can be used to clip the rate used in bulk, if necessary uint256 public maximumRate = 5000; // @notice The address of the store selling products address public storeAddress; // @notice The contract is retired // @dev If we decide to retire this program, this value will be set to true // and then the contract cannot be unpaused bool public retired = false; /** * @dev Modifier to make a function only callable by the store or the owner */ modifier onlyStoreOrOwner() { require( msg.sender == storeAddress || msg.sender == owner); _; } /** * @dev AffiliateProgram constructor - keeps the address of it's parent store * and pauses the contract */ function AffiliateProgram(address _storeAddress) public { require(_storeAddress != address(0)); storeAddress = _storeAddress; paused = true; } /** * @notice Exposes that this contract thinks it is an AffiliateProgram */ function isAffiliateProgram() public pure returns (bool) { return true; } /** * @notice returns the commission rate for a sale * * @dev rateFor returns the rate which should be used to calculate the comission * for this affiliate/sale combination, in basis points (1/100th of a percent). * * We may want to completely blacklist a particular address (e.g. a known bad actor affilite). * To that end, if the whitelistRate is exactly 1bp, we use that as a signal for blacklisting * and return a rate of zero. The upside is that we can completely turn off * sending transactions to a particular address when this is needed. The * downside is that you can't issued 1/100th of a percent commission. * However, since this is such a small amount its an acceptable tradeoff. * * This implementation does not use the _productId, _pruchaseId, * _purchaseAmount, but we include them here as part of the protocol, because * they could be useful in more advanced affiliate programs. * * @param _affiliate - the address of the affiliate to check for */ function rateFor( address _affiliate, uint256 /*_productId*/, uint256 /*_purchaseId*/, uint256 /*_purchaseAmount*/) public view returns (uint256) { uint256 whitelistedRate = whitelistRates[_affiliate]; if(whitelistedRate > 0) { // use 1 bp as a blacklist signal if(whitelistedRate == 1) { return 0; } else { return Math.min256(whitelistedRate, maximumRate); } } else { return Math.min256(baselineRate, maximumRate); } } /** * @notice cutFor returns the affiliate cut for a sale * @dev cutFor returns the cut (amount in wei) to give in comission to the affiliate * * @param _affiliate - the address of the affiliate to check for * @param _productId - the productId in the sale * @param _purchaseId - the purchaseId in the sale * @param _purchaseAmount - the purchaseAmount */ function cutFor( address _affiliate, uint256 _productId, uint256 _purchaseId, uint256 _purchaseAmount) public view returns (uint256) { uint256 rate = rateFor( _affiliate, _productId, _purchaseId, _purchaseAmount); require(rate <= hardCodedMaximumRate); return (_purchaseAmount.mul(rate)).div(10000); } /** * @notice credit an affiliate for a purchase * @dev credit accepts eth and credits the affiliate's balance for the amount * * @param _affiliate - the address of the affiliate to credit * @param _purchaseId - the purchaseId of the sale */ function credit( address _affiliate, uint256 _purchaseId) public onlyStoreOrOwner whenNotPaused payable { require(msg.value > 0); require(_affiliate != address(0)); balances[_affiliate] += msg.value; lastDepositTimes[_affiliate] = now; // solium-disable-line security/no-block-members lastDepositTime = now; // solium-disable-line security/no-block-members AffiliateCredit(_affiliate, _purchaseId, msg.value); } /** * @dev _performWithdraw performs a withdrawal from address _from and * transfers it to _to. This can be different because we allow the owner * to withdraw unclaimed funds after a period of time. * * @param _from - the address to subtract balance from * @param _to - the address to transfer ETH to */ function _performWithdraw(address _from, address _to) private { require(balances[_from] > 0); uint256 balanceValue = balances[_from]; balances[_from] = 0; _to.transfer(balanceValue); Withdraw(_from, _to, balanceValue); } /** * @notice withdraw * @dev withdraw the msg.sender's balance */ function withdraw() public whenNotPaused { _performWithdraw(msg.sender, msg.sender); } /** * @notice withdraw from a specific account * @dev withdrawFrom allows the owner to withdraw an affiliate's unclaimed * ETH, after the alotted time. * * This function can be called even if the contract is paused * * @param _affiliate - the address of the affiliate * @param _to - the address to send ETH to */ function withdrawFrom(address _affiliate, address _to) onlyOwner public { // solium-disable-next-line security/no-block-members require(now > lastDepositTimes[_affiliate].add(commissionExpiryTime)); _performWithdraw(_affiliate, _to); } /** * @notice retire the contract (dangerous) * @dev retire - withdraws the entire balance and marks the contract as retired, which * prevents unpausing. * * If no new comissions have been deposited for the alotted time, * then the owner may pause the program and retire this contract. * This may only be performed once as the contract cannot be unpaused. * * We do this as an alternative to selfdestruct, because certain operations * can still be performed after the contract has been selfdestructed, such as * the owner withdrawing ETH accidentally sent here. */ function retire(address _to) onlyOwner whenPaused public { // solium-disable-next-line security/no-block-members require(now > lastDepositTime.add(commissionExpiryTime)); _to.transfer(this.balance); retired = true; } /** * @notice whitelist an affiliate address * @dev whitelist - white listed affiliates can receive a different * rate than the general public (whitelisted accounts would generally get a * better rate). * @param _affiliate - the affiliate address to whitelist * @param _rate - the rate, in basis-points (1/100th of a percent) to give this affiliate in each sale. NOTE: a rate of exactly 1 is the signal to blacklist this affiliate. That is, a rate of 1 will set the commission to 0. */ function whitelist(address _affiliate, uint256 _rate) onlyOwner public { require(_rate <= hardCodedMaximumRate); whitelistRates[_affiliate] = _rate; Whitelisted(_affiliate, _rate); } /** * @notice set the rate for non-whitelisted affiliates * @dev setBaselineRate - sets the baseline rate for any affiliate that is not whitelisted * @param _newRate - the rate, in bp (1/100th of a percent) to give any non-whitelisted affiliate. Set to zero to "turn off" */ function setBaselineRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); baselineRate = _newRate; RateChanged(0, _newRate); } /** * @notice set the maximum rate for any affiliate * @dev setMaximumRate - Set the maximum rate for any affiliate, including whitelists. That is, this overrides individual rates. * @param _newRate - the rate, in bp (1/100th of a percent) */ function setMaximumRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); maximumRate = _newRate; RateChanged(1, _newRate); } /** * @notice unpause the contract * @dev called by the owner to unpause, returns to normal state. Will not * unpause if the contract is retired. */ function unpause() onlyOwner whenPaused public { require(!retired); paused = false; Unpause(); } } contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) external; function setApprovalForAll(address _to, bool _approved) external; function getApproved(uint256 _tokenId) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool); } contract LicenseInventory is LicenseBase { using SafeMath for uint256; event ProductCreated( uint256 id, uint256 price, uint256 available, uint256 supply, uint256 interval, bool renewable ); event ProductInventoryAdjusted(uint256 productId, uint256 available); event ProductPriceChanged(uint256 productId, uint256 price); event ProductRenewableChanged(uint256 productId, bool renewable); /** * @notice Product defines a product * * renewable: There may come a time when we which to disable the ability to renew a subscription. For example, a plan we no longer wish to support. Obviously care needs to be taken with how we communicate this to customers, but contract-wise, we want to support the ability to discontinue renewal of certain plans. */ struct Product { uint256 id; uint256 price; uint256 available; uint256 supply; uint256 sold; uint256 interval; bool renewable; } // @notice All products in existence uint256[] public allProductIds; // @notice A mapping from product ids to Products mapping (uint256 => Product) public products; /*** internal ***/ /** * @notice _productExists checks to see if a product exists */ function _productExists(uint256 _productId) internal view returns (bool) { return products[_productId].id != 0; } function _productDoesNotExist(uint256 _productId) internal view returns (bool) { return products[_productId].id == 0; } function _createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) internal { require(_productDoesNotExist(_productId)); require(_initialInventoryQuantity <= _supply); Product memory _product = Product({ id: _productId, price: _initialPrice, available: _initialInventoryQuantity, supply: _supply, sold: 0, interval: _interval, renewable: _interval == 0 ? false : true }); products[_productId] = _product; allProductIds.push(_productId); ProductCreated( _product.id, _product.price, _product.available, _product.supply, _product.interval, _product.renewable ); } function _incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.add(_inventoryAdjustment); // A supply of "0" means "unlimited". Otherwise we need to ensure that we're not over-creating this product if(products[_productId].supply > 0) { // you have to take already sold into account require(products[_productId].sold.add(newInventoryLevel) <= products[_productId].supply); } products[_productId].available = newInventoryLevel; } function _decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.sub(_inventoryAdjustment); // unnecessary because we're using SafeMath and an unsigned int // require(newInventoryLevel >= 0); products[_productId].available = newInventoryLevel; } function _clearInventory(uint256 _productId) internal { require(_productExists(_productId)); products[_productId].available = 0; } function _setPrice(uint256 _productId, uint256 _price) internal { require(_productExists(_productId)); products[_productId].price = _price; } function _setRenewable(uint256 _productId, bool _isRenewable) internal { require(_productExists(_productId)); products[_productId].renewable = _isRenewable; } function _purchaseOneUnitInStock(uint256 _productId) internal { require(_productExists(_productId)); require(availableInventoryOf(_productId) > 0); // lower inventory _decrementInventory(_productId, 1); // record that one was sold products[_productId].sold = products[_productId].sold.add(1); } function _requireRenewableProduct(uint256 _productId) internal view { // productId must exist require(_productId != 0); // You can only renew a subscription product require(isSubscriptionProduct(_productId)); // The product must currently be renewable require(renewableOf(_productId)); } /*** public ***/ /** executives-only **/ /** * @notice createProduct creates a new product in the system * @param _productId - the id of the product to use (cannot be changed) * @param _initialPrice - the starting price (price can be changed) * @param _initialInventoryQuantity - the initial inventory (inventory can be changed) * @param _supply - the total supply - use `0` for "unlimited" (cannot be changed) */ function createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) external onlyCEOOrCOO { _createProduct( _productId, _initialPrice, _initialInventoryQuantity, _supply, _interval); } /** * @notice incrementInventory - increments the inventory of a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to increment */ function incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _incrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice decrementInventory removes inventory levels for a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to decrement */ function decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _decrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice clearInventory clears the inventory of a product. * @dev decrementInventory verifies inventory levels, whereas this method * simply sets the inventory to zero. This is useful, for example, if an * executive wants to take a product off the market quickly. There could be a * race condition with decrementInventory where a product is sold, which could * cause the admins decrement to fail (because it may try to decrement more * than available). * * @param _productId - the product id */ function clearInventory(uint256 _productId) external onlyCLevel { _clearInventory(_productId); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice setPrice - sets the price of a product * @param _productId - the product id * @param _price - the product price */ function setPrice(uint256 _productId, uint256 _price) external onlyCLevel { _setPrice(_productId, _price); ProductPriceChanged(_productId, _price); } /** * @notice setRenewable - sets if a product is renewable * @param _productId - the product id * @param _newRenewable - the new renewable setting */ function setRenewable(uint256 _productId, bool _newRenewable) external onlyCLevel { _setRenewable(_productId, _newRenewable); ProductRenewableChanged(_productId, _newRenewable); } /** anyone **/ /** * @notice The price of a product * @param _productId - the product id */ function priceOf(uint256 _productId) public view returns (uint256) { return products[_productId].price; } /** * @notice The available inventory of a product * @param _productId - the product id */ function availableInventoryOf(uint256 _productId) public view returns (uint256) { return products[_productId].available; } /** * @notice The total supply of a product * @param _productId - the product id */ function totalSupplyOf(uint256 _productId) public view returns (uint256) { return products[_productId].supply; } /** * @notice The total sold of a product * @param _productId - the product id */ function totalSold(uint256 _productId) public view returns (uint256) { return products[_productId].sold; } /** * @notice The renewal interval of a product in seconds * @param _productId - the product id */ function intervalOf(uint256 _productId) public view returns (uint256) { return products[_productId].interval; } /** * @notice Is this product renewable? * @param _productId - the product id */ function renewableOf(uint256 _productId) public view returns (bool) { return products[_productId].renewable; } /** * @notice The product info for a product * @param _productId - the product id */ function productInfo(uint256 _productId) public view returns (uint256, uint256, uint256, uint256, bool) { return ( priceOf(_productId), availableInventoryOf(_productId), totalSupplyOf(_productId), intervalOf(_productId), renewableOf(_productId)); } /** * @notice Get all product ids */ function getAllProductIds() public view returns (uint256[]) { return allProductIds; } /** * @notice returns the total cost to renew a product for a number of cycles * @dev If a product is a subscription, the interval defines the period of * time, in seconds, users can subscribe for. E.g. 1 month or 1 year. * _numCycles is the number of these intervals we want to use in the * calculation of the price. * * We require that the end user send precisely the amount required (instead * of dealing with excess refunds). This method is public so that clients can * read the exact amount our contract expects to receive. * * @param _productId - the product we're calculating for * @param _numCycles - the number of cycles to calculate for */ function costForProductCycles(uint256 _productId, uint256 _numCycles) public view returns (uint256) { return priceOf(_productId).mul(_numCycles); } /** * @notice returns if this product is a subscription or not * @dev Some products are subscriptions and others are not. An interval of 0 * means the product is not a subscription * @param _productId - the product we're checking */ function isSubscriptionProduct(uint256 _productId) public view returns (bool) { return intervalOf(_productId) > 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract LicenseOwnership is LicenseInventory, ERC721, ERC165, ERC721Metadata, ERC721Enumerable { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner address to operator address to approval mapping (address => mapping (address => bool)) private operatorApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /*** Constants ***/ // Configure these for your own deployment string public constant NAME = "Dottabot"; string public constant SYMBOL = "DOTTA"; string public tokenMetadataBaseURI = "https://api.dottabot.com/"; /** * @notice token's name */ function name() external pure returns (string) { return NAME; } /** * @notice symbols's name */ function symbol() external pure returns (string) { return SYMBOL; } function implementsERC721() external pure returns (bool) { return true; } function tokenURI(uint256 _tokenId) external view returns (string infoUrl) { return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId)); } function supportsInterface( bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments external view returns (bool) { return interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x6466353c || // ERC-721 on 3/7/2018 interfaceID == 0x780e9d63; // ERC721Enumerable } function setTokenMetadataBaseURI(string _newBaseURI) external onlyCEOOrCOO { tokenMetadataBaseURI = _newBaseURI; } /** * @notice Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @notice Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @notice Enumerate valid NFTs * @dev Our Licenses are kept in an array and each new License-token is just * the next element in the array. This method is required for ERC721Enumerable * which may support more complicated storage schemes. However, in our case the * _index is the tokenId * @param _index A counter less than `totalSupply()` * @return The token identifier for the `_index`th NFT */ function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < totalSupply()); return _index; } /** * @notice Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokens[_owner].length; } /** * @notice Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @notice Enumerate NFTs assigned to an owner * @dev Throws if `_index` >= `balanceOf(_owner)` or if * `_owner` is the zero address, representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them * @param _index A counter less than `balanceOf(_owner)` * @return The token identifier for the `_index`th NFT assigned to `_owner`, */ function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @notice Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @notice Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @notice Tells whether the msg.sender is approved to transfer the given token ID or not * Checks both for specific approval and operator approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether transfer by msg.sender is approved for the given token ID or not */ function isSenderApprovedFor(uint256 _tokenId) internal view returns (bool) { return ownerOf(_tokenId) == msg.sender || isSpecificallyApprovedFor(msg.sender, _tokenId) || isApprovedForAll(ownerOf(_tokenId), msg.sender); } /** * @notice Tells whether the msg.sender is approved for the given token ID or not * @param _asker address of asking for approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) { return getApproved(_tokenId) == _asker; } /** * @notice Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @notice Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) external whenNotPaused onlyOwnerOf(_tokenId) { _clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @notice Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) external whenNotPaused onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (getApproved(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @notice Enable or disable approval for a third party ("operator") to manage all your assets * @dev Emits the ApprovalForAll event * @param _to Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval */ function setApprovalForAll(address _to, bool _approved) external whenNotPaused { if(_approved) { approveAll(_to); } else { disapproveAll(_to); } } /** * @notice Approves another address to claim for the ownership of any tokens owned by this account * @param _to address to be approved for the given token ID */ function approveAll(address _to) public whenNotPaused { require(_to != msg.sender); require(_to != address(0)); operatorApprovals[msg.sender][_to] = true; ApprovalForAll(msg.sender, _to, true); } /** * @notice Removes approval for another address to claim for the ownership of any * tokens owned by this account. * @dev Note that this only removes the operator approval and * does not clear any independent, specific approvals of token transfers to this address * @param _to address to be disapproved for the given token ID */ function disapproveAll(address _to) public whenNotPaused { require(_to != msg.sender); delete operatorApprovals[msg.sender][_to]; ApprovalForAll(msg.sender, _to, false); } /** * @notice Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) external whenNotPaused { require(isSenderApprovedFor(_tokenId)); _clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @notice Transfer a token 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 token * @param _to The address that will take ownership of the token. Can be any address, including the caller * @param _tokenId The ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { require(isSenderApprovedFor(_tokenId)); require(ownerOf(_tokenId) == _from); _clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId); } /** * @notice Transfers the ownership of an NFT from one address to another address * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. When transfer is complete, this function * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public whenNotPaused { require(_to != address(0)); require(_isValidLicense(_tokenId)); transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)( _from, _tokenId, _data ); require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /* * @notice Transfers the ownership of an NFT from one address to another address * @dev This works identically to the other function with an extra data parameter, * except this function just sets data to "" * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @notice Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); _addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @notice Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function _clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); require(_isValidLicense(_tokenId)); _clearApproval(_from, _tokenId); _removeToken(_from, _tokenId); _addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @notice Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @notice Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @notice Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } function _isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } contract LicenseSale is LicenseOwnership { AffiliateProgram public affiliateProgram; /** * @notice We credit affiliates for renewals that occur within this time of * original purchase. E.g. If this is set to 1 year, and someone subscribes to * a monthly plan, the affiliate will receive credits for that whole year, as * the user renews their plan */ uint256 public renewalsCreditAffiliatesFor = 1 years; /** internal **/ function _performPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { _purchaseOneUnitInStock(_productId); return _createLicense( _productId, _numCycles, _assignee, _attributes, _affiliate ); } function _createLicense( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { // You cannot create a subscription license with zero cycles if(isSubscriptionProduct(_productId)) { require(_numCycles != 0); } // Non-subscription products have an expiration time of 0, meaning "no-expiration" uint256 expirationTime = isSubscriptionProduct(_productId) ? now.add(intervalOf(_productId).mul(_numCycles)) : // solium-disable-line security/no-block-members 0; License memory _license = License({ productId: _productId, attributes: _attributes, issuedTime: now, // solium-disable-line security/no-block-members expirationTime: expirationTime, affiliate: _affiliate }); uint256 newLicenseId = licenses.push(_license) - 1; // solium-disable-line zeppelin/no-arithmetic-operations LicenseIssued( _assignee, msg.sender, newLicenseId, _license.productId, _license.attributes, _license.issuedTime, _license.expirationTime, _license.affiliate); _mint(_assignee, newLicenseId); return newLicenseId; } function _handleAffiliate( address _affiliate, uint256 _productId, uint256 _licenseId, uint256 _purchaseAmount) internal { uint256 affiliateCut = affiliateProgram.cutFor( _affiliate, _productId, _licenseId, _purchaseAmount); if(affiliateCut > 0) { require(affiliateCut < _purchaseAmount); affiliateProgram.credit.value(affiliateCut)(_affiliate, _licenseId); } } function _performRenewal(uint256 _tokenId, uint256 _numCycles) internal { // You cannot renew a non-expiring license // ... but in what scenario can this happen? // require(licenses[_tokenId].expirationTime != 0); uint256 productId = licenseProductId(_tokenId); // If our expiration is in the future, renewing adds time to that future expiration // If our expiration has passed already, then we use `now` as the base. uint256 renewalBaseTime = Math.max256(now, licenses[_tokenId].expirationTime); // We assume that the payment has been validated outside of this function uint256 newExpirationTime = renewalBaseTime.add(intervalOf(productId).mul(_numCycles)); licenses[_tokenId].expirationTime = newExpirationTime; LicenseRenewal( ownerOf(_tokenId), msg.sender, _tokenId, productId, newExpirationTime ); } function _affiliateProgramIsActive() internal view returns (bool) { return affiliateProgram != address(0) && affiliateProgram.storeAddress() == address(this) && !affiliateProgram.paused(); } /** executives **/ function setAffiliateProgramAddress(address _address) external onlyCEO { AffiliateProgram candidateContract = AffiliateProgram(_address); require(candidateContract.isAffiliateProgram()); affiliateProgram = candidateContract; } function setRenewalsCreditAffiliatesFor(uint256 _newTime) external onlyCEO { renewalsCreditAffiliatesFor = _newTime; } function createPromotionalPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes ) external onlyCEOOrCOO whenNotPaused returns (uint256) { return _performPurchase( _productId, _numCycles, _assignee, _attributes, address(0)); } function createPromotionalRenewal( uint256 _tokenId, uint256 _numCycles ) external onlyCEOOrCOO whenNotPaused { uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); return _performRenewal(_tokenId, _numCycles); } /** anyone **/ /** * @notice Makes a purchase of a product. * @dev Requires that the value sent is exactly the price of the product * @param _productId - the product to purchase * @param _numCycles - the number of cycles being purchased. This number should be `1` for non-subscription products and the number of cycles for subscriptions. * @param _assignee - the address to assign the purchase to (doesn't have to be msg.sender) * @param _affiliate - the address to of the affiliate - use address(0) if none */ function purchase( uint256 _productId, uint256 _numCycles, address _assignee, address _affiliate ) external payable whenNotPaused returns (uint256) { require(_productId != 0); require(_numCycles != 0); require(_assignee != address(0)); // msg.value can be zero: free products are supported // Don't bother dealing with excess payments. Ensure the price paid is // accurate. No more, no less. require(msg.value == costForProductCycles(_productId, _numCycles)); // Non-subscription products should send a _numCycle of 1 -- you can't buy a // multiple quantity of a non-subscription product with this function if(!isSubscriptionProduct(_productId)) { require(_numCycles == 1); } // this can, of course, be gamed by malicious miners. But it's adequate for our application // Feel free to add your own strategies for product attributes // solium-disable-next-line security/no-block-members, zeppelin/no-arithmetic-operations uint256 attributes = uint256(keccak256(block.blockhash(block.number-1)))^_productId^(uint256(_assignee)); uint256 licenseId = _performPurchase( _productId, _numCycles, _assignee, attributes, _affiliate); if( priceOf(_productId) > 0 && _affiliate != address(0) && _affiliateProgramIsActive() ) { _handleAffiliate( _affiliate, _productId, licenseId, msg.value); } return licenseId; } /** * @notice Renews a subscription */ function renew( uint256 _tokenId, uint256 _numCycles ) external payable whenNotPaused { require(_numCycles != 0); require(ownerOf(_tokenId) != address(0)); uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); // No excess payments. Ensure the price paid is exactly accurate. No more, // no less. uint256 renewalCost = costForProductCycles(productId, _numCycles); require(msg.value == renewalCost); _performRenewal(_tokenId, _numCycles); if( renewalCost > 0 && licenseAffiliate(_tokenId) != address(0) && _affiliateProgramIsActive() && licenseIssuedTime(_tokenId).add(renewalsCreditAffiliatesFor) > now ) { _handleAffiliate( licenseAffiliate(_tokenId), productId, _tokenId, msg.value); } } } contract LicenseCore is LicenseSale { address public newContractAddress; function LicenseCore() public { paused = true; ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; withdrawalAddress = msg.sender; } function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function() external { assert(false); } function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0)); super.unpause(); } } library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol 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, "", "", ""); } 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); } }
* @notice withdraw @dev withdraw the msg.sender's balance/
function withdraw() public whenNotPaused { _performWithdraw(msg.sender, msg.sender); }
478,419
[ 1, 1918, 9446, 225, 598, 9446, 326, 1234, 18, 15330, 1807, 11013, 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, 445, 598, 9446, 1435, 1071, 1347, 1248, 28590, 288, 203, 565, 389, 16092, 1190, 9446, 12, 3576, 18, 15330, 16, 1234, 18, 15330, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract RSEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularRatScam is RSEvents {} contract ChivesGarden is modularRatScam { using SafeMath for *; using NameFilter for string; using RSKeysCalc for uint256; // TODO: check address BankInterfaceForForwarder constant private Bank = BankInterfaceForForwarder(0xfa1678C00299fB685794865eA5e20dB155a8C913); ChivesBookInterface constant private ChivesBook = ChivesBookInterface(0xE7D91A421D816349Cf0CD9C4b7a10123C2B28125); address private admin = msg.sender; string constant public name = "Chives Garden"; string constant public symbol = "Chives"; // TODO: check time uint256 private rndGap_ = 0; uint256 private rndExtra_ = 0 minutes; uint256 constant private rndInit_ = 24 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => RSdatasets.PlayerRounds) public plyrRnds_; // current round mapping (uint256 => mapping (uint256 => RSdatasets.PlayerRounds)) public plyrRnds; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** uint256 public rID_; // round id number / total rounds that have happened RSdatasets.Round public round_; // round data mapping (uint256 => RSdatasets.Round) public round; // current round //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 60; // fee distribution uint256 public potSplit_ = 45; // pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } /** * @dev prevents contracts from interacting with ratscam */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "non smart contract address only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round[_rID].end && round[_rID].ended == false && round[_rID].plyr != 0) { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = ChivesBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = ChivesBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = ChivesBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) return ( (round[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round[_rID].end) if (_now > round[_rID].strt + rndGap_) return( (round[_rID].end).sub(_now) ); else return( (round[_rID].strt + rndGap_).sub(_now)); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round[_rID].end && round[_rID].ended == false && round[_rID].plyr != 0) { // if player is winner if (round[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds[_pID][_rID].mask) ), plyr_[_pID].aff ); } plyrRnds_[_pID] = plyrRnds[_pID][_rID]; // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round[_rID].mask).add(((((round[_rID].pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round[_rID].keys))).mul(plyrRnds[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { uint256 _rID = rID_; return ( round[_rID].keys, //0 round[_rID].end, //1 round[_rID].strt, //2 round[_rID].pot, //3 round[_rID].plyr, //4 plyr_[round[_rID].plyr].addr, //5 plyr_[round[_rID].plyr].name, //6 airDropTracker_ + (airDropPot_ * 1000) //7 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round[_rID].end && round[_rID].ended == false) { // end the round (distributes pot) & start new round round[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, RSdatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round[_rID].end && round[_rID].ended == false) { // end the round (distributes pot) & start new round round[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RSEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round[_rID].eth < 100000000000000000000 && plyrRnds[_pID][_rID].eth.add(_eth) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).sub(plyrRnds[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round[_rID].plyr != _pID) round[_rID].plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds[_pID][_rID].keys = _keys.add(plyrRnds[_pID][_rID].keys); plyrRnds[_pID][_rID].eth = _eth.add(plyrRnds[_pID][_rID].eth); // update round round[_rID].keys = _keys.add(round[_rID].keys); round[_rID].eth = _eth.add(round[_rID].eth); // distribute eth _eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } plyrRnds_[_pID] = plyrRnds[_pID][_rID]; round_ = round[_rID]; } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return((((round[_rIDlast].mask).mul(plyrRnds[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds[_pID][_rIDlast].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _eth) public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) return ( (round[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round[_rID].strt + rndGap_ && (_now <= round[_rID].end || (_now > round[_rID].end && round[_rID].plyr == 0))) return ( (round[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(ChivesBook), "only ChivesBook can call this function"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(ChivesBook), "only ChivesBook can call this function"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of ratscam if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = ChivesBook.getPlayerID(msg.sender); bytes32 _name = ChivesBook.getPlayerName(_pID); uint256 _laff = ChivesBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round[_rID].plyr; // grab our pot amount // add airdrop pot into the final pot // uint256 _pot = round[_rID].pot + airDropPot_; uint256 _pot = round[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards // if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()")))) // { // _gen = _gen.add(_com); // _com = 0; // } // distribute gen portion to key holders round[_rID].mask = _ppt.add(round[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _com; // start next round rID_++; _rID++; round[_rID].strt = now + rndExtra_; round[_rID].end = now + rndInit_ + rndExtra_; round[_rID].pot = _com; round_ = round[_rID]; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds[_pID][_rIDlast].mask = _earnings.add(plyrRnds[_pID][_rIDlast].mask); plyrRnds_[_pID] = plyrRnds[_pID][_rIDlast]; } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round[_rID].end && round[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round[_rID].end = _newTime; else round[_rID].end = rndMax_.add(_now); round_ = round[_rID]; } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth * 5 / 100; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { // no affiliates, add to community _com += _aff; } if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. } return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot (20%) uint256 _pot = (_eth.mul(20) / 100); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round[_rID].pot = _pot.add(_dust).add(round[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; round_ = round[_rID]; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round[_rID].keys); round[_rID].mask = _ppt.add(round[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds[_pID][_rID].mask = (((round[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds[_pID][_rID].mask); plyrRnds_[_pID] = plyrRnds[_pID][_rID]; round_ = round[_rID]; // calculate & return dust return(_gen.sub((_ppt.mul(round[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit RSEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only owner can activate // TODO: set owner require(msg.sender == admin); // can only be ran once require(activated_ == false, "ratscam already activated"); // activate the contract activated_ = true; rID_ = 1; round[1].strt = now + rndExtra_; round[1].end = now + rndInit_ + rndExtra_; round_ = round[1]; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library RSdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library RSKeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface BankInterfaceForForwarder { function deposit() external payable returns(bool); } interface ChivesBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } }
only owner can activate TODO: set owner can only be ran once activate the contract
function activate() public { require(msg.sender == admin); require(activated_ == false, "ratscam already activated"); activated_ = true; rID_ = 1; round[1].strt = now + rndExtra_; round[1].end = now + rndInit_ + rndExtra_; round_ = round[1]; }
338,468
[ 1, 3700, 3410, 848, 10235, 2660, 30, 444, 3410, 848, 1338, 506, 18892, 3647, 10235, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10235, 1435, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 1769, 203, 540, 203, 3639, 2583, 12, 18836, 67, 422, 629, 16, 315, 17048, 1017, 301, 1818, 14892, 8863, 203, 540, 203, 3639, 14892, 67, 273, 638, 31, 203, 540, 203, 3639, 436, 734, 67, 273, 404, 31, 203, 3639, 3643, 63, 21, 8009, 701, 88, 273, 2037, 397, 20391, 7800, 67, 31, 203, 3639, 3643, 63, 21, 8009, 409, 273, 2037, 397, 20391, 2570, 67, 397, 20391, 7800, 67, 31, 203, 3639, 3643, 67, 273, 3643, 63, 21, 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 ]
./full_match/80001/0xb1B3D50811731f55543152FA134D0EF44f082cb6/sources/contracts/Gateway/ClaimHelper.sol
For stablecoins devaluation will decided based on oracle Calculate Payout Set cover to payout set state var for store payour per request/offer Get cover offer Update total payout of offer cover Get cover request Update total payout of offer request
function _checkValidity(uint256 _claimId, address _priceFeedAddr) internal { Claim memory claim = claimData.getClaimById(_claimId); ( bool isClaimValid, uint256 assetPrice, uint8 decimals ) = checkClaimForDevaluation(_priceFeedAddr, claim.roundId); uint256 coverId = claimData.claimToCover(_claimId); if (isClaimValid) { uint256 payout = 0; InsuranceCover memory cover = coverData.getCoverById(coverId); payout = getPayout(cover, assetPrice, decimals); require( claimData.coverToPayout(coverId) + payout <= cover.insuredSum, "Claim Gateway: Insufficient funds" ); claimData.setCoverToPayout(coverId, payout); CurrencyType currency; if (cover.listingType == ListingType.OFFER) { CoverOffer memory coverOffer = listingData.getCoverOfferById( cover.offerId ); currency = coverOffer.insuredSumCurrency; claimData.setOfferIdToPayout(cover.offerId, payout); CoverRequest memory coverRequest = listingData .getCoverRequestById(cover.requestId); currency = coverRequest.insuredSumCurrency; claimData.setRequestIdToPayout(cover.requestId, payout); } _claimId, ClaimState.VALID_AFTER_EXPIRED ); emit ExpiredValidClaim(coverId, _claimId, uint8(currency), payout); _claimId, ClaimState.INVALID_AFTER_EXPIRED ); emit ExpiredInvalidClaim(coverId, _claimId); } }
9,504,958
[ 1, 1290, 14114, 71, 9896, 4461, 700, 367, 903, 2109, 13898, 2511, 603, 20865, 9029, 453, 2012, 1000, 5590, 358, 293, 2012, 444, 919, 569, 364, 1707, 8843, 477, 1534, 590, 19, 23322, 968, 5590, 10067, 2315, 2078, 293, 2012, 434, 10067, 5590, 968, 5590, 590, 2315, 2078, 293, 2012, 434, 10067, 590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1893, 19678, 12, 11890, 5034, 389, 14784, 548, 16, 1758, 389, 8694, 8141, 3178, 13, 2713, 288, 203, 3639, 18381, 3778, 7516, 273, 7516, 751, 18, 588, 9762, 5132, 24899, 14784, 548, 1769, 203, 203, 3639, 261, 203, 5411, 1426, 353, 9762, 1556, 16, 203, 5411, 2254, 5034, 3310, 5147, 16, 203, 5411, 2254, 28, 15105, 203, 3639, 262, 273, 866, 9762, 1290, 758, 4531, 367, 24899, 8694, 8141, 3178, 16, 7516, 18, 2260, 548, 1769, 203, 203, 3639, 2254, 5034, 5590, 548, 273, 7516, 751, 18, 14784, 774, 8084, 24899, 14784, 548, 1769, 203, 3639, 309, 261, 291, 9762, 1556, 13, 288, 203, 5411, 2254, 5034, 293, 2012, 273, 374, 31, 203, 5411, 657, 10050, 1359, 8084, 3778, 5590, 273, 5590, 751, 18, 588, 8084, 5132, 12, 3165, 548, 1769, 203, 5411, 293, 2012, 273, 1689, 2012, 12, 3165, 16, 3310, 5147, 16, 15105, 1769, 203, 5411, 2583, 12, 203, 7734, 7516, 751, 18, 3165, 774, 52, 2012, 12, 3165, 548, 13, 397, 293, 2012, 1648, 5590, 18, 267, 2055, 72, 3495, 16, 203, 7734, 315, 9762, 11381, 30, 22085, 11339, 284, 19156, 6, 203, 5411, 11272, 203, 203, 5411, 7516, 751, 18, 542, 8084, 774, 52, 2012, 12, 3165, 548, 16, 293, 2012, 1769, 203, 203, 5411, 13078, 559, 5462, 31, 203, 5411, 309, 261, 3165, 18, 21228, 559, 422, 987, 310, 559, 18, 8797, 654, 13, 288, 203, 7734, 23293, 10513, 3778, 5590, 10513, 273, 11591, 751, 18, 588, 8084, 10513, 5132, 12, 203, 10792, 5590, 18, 23322, 2 ]
pragma solidity ^0.4.23; 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 /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). **/ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. **/ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". **/ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. **/ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. **/ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. **/ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic interface * @dev Basic ERC20 interface **/ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 **/ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. **/ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Configurable * @dev Configurable varriables of the contract **/ contract Configurable { uint256 public constant cap = 400000000000000000*10**1; uint256 public constant basePrice = 1000000000000000*10**1; // tokens per 1 ether uint256 public tokensSold = 0; uint256 public constant tokenReserve = 80000000000000000*10**1; uint256 public remainingTokens = 0; } /** * @title CrowdsaleToken * @dev Contract to preform crowd sale with token **/ contract CrowdsaleToken is StandardToken, Configurable, Ownable { /** * @dev enum of current crowd sale state **/ enum Stages { none, icoStart, icoEnd } Stages currentStage; /** * @dev constructor of CrowdsaleToken **/ constructor() public { currentStage = Stages.none; balances[owner] = balances[owner].add(tokenReserve); totalSupply_ = totalSupply_.add(tokenReserve); remainingTokens = cap; emit Transfer(address(this), owner, tokenReserve); } /** * @dev fallback function to send ether to for Crowd sale **/ function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.add(tokens); // Increment raised amount remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); owner.transfer(weiAmount);// Send money to owner } /** * @dev startIco starts the public ICO **/ function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; } /** * @dev endIco closes down the ICO **/ function endIco() internal { currentStage = Stages.icoEnd; // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); } /** * @dev finalizeIco closes down the ICO and sets needed varriables **/ function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); } } /** * @title RetrieverCoin * @dev Contract to create the Retriever Coin **/ contract RetrieverCoin is CrowdsaleToken { string public constant name = "Retriever Coin"; string public constant symbol = "RETR"; uint32 public constant decimals = 1; }
* @title Configurable @dev Configurable varriables of the contract/
contract Configurable { uint256 public constant cap = 400000000000000000*10**1; uint256 public tokensSold = 0; uint256 public constant tokenReserve = 80000000000000000*10**1; uint256 public remainingTokens = 0; }
14,501,532
[ 1, 31660, 225, 29312, 569, 566, 1538, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 29312, 288, 203, 565, 2254, 5034, 1071, 5381, 3523, 273, 1059, 12648, 2787, 11706, 14, 2163, 636, 21, 31, 203, 565, 2254, 5034, 1071, 2430, 55, 1673, 273, 374, 31, 203, 377, 203, 565, 2254, 5034, 1071, 5381, 1147, 607, 6527, 273, 1725, 12648, 12648, 14, 2163, 636, 21, 31, 203, 565, 2254, 5034, 1071, 4463, 5157, 273, 374, 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 ]
./partial_match/1/0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b/sources/Token.sol
require user to set to zero before resetting to nonzero
function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) { if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; } allowance[_owner][_spender] = _value; return true; }
9,284,127
[ 1, 6528, 729, 358, 444, 358, 3634, 1865, 30691, 358, 16966, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6617, 537, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 16, 2254, 389, 1132, 13, 203, 565, 1338, 2933, 203, 565, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 309, 14015, 67, 1132, 480, 374, 13, 597, 261, 5965, 1359, 63, 67, 8443, 6362, 67, 87, 1302, 264, 65, 480, 374, 3719, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 1699, 1359, 63, 67, 8443, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "./IRainiCard.sol"; import "../tokens/IRainiCustomNFT.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; interface INftStakingPool { function getTokenStaminaTotal(uint256 _tokenId, address _nftContractAddress) external view returns (uint32 stamina); function setTokenStaminaTotal(uint32 _stamina, uint256 _tokenId, address _nftContractAddress) external; } contract MainnetNftBridgePool is IERC721Receiver, IERC1155Receiver, AccessControl, ReentrancyGuard { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); event CardsDeposited( uint256 nftContractId, address indexed spender, address recipient, uint256 amount, uint256 requestId, uint128 cardId, uint32 level, uint32 number, uint32 stamina, bytes1 mintedContractChar, bytes state ); event EthWithdrawn(uint256 amount); event AutoWithdrawFeeSet(bool autoWithdraw); event ConfigSet(address cardToken, address nftV1Token, address nftV2Token); event TreasuryAddressSet(address treasuryAddress); event FeesSet(uint256 card, uint256 nftV1, uint256 nftV2); event ItemFeeSet(uint256 card, uint256 nftV1, uint256 nftV2); event CardsWithdrawn(uint256 nftContractId, address indexed owner, uint256 requestId, uint256 cardId, uint256 amount); mapping(uint256 => address) public nftContracts; mapping(uint256 => bool) public hasSubcontracts; // contractId => cardId => bool mapping(uint256 => mapping(uint256 => bool)) public cardDisabled; // _contractId => _cardId => _cardLevel => _mintedContractChar => uint256 _number mapping(uint256 => mapping(uint256 => mapping(uint256 => mapping(bytes1 => mapping(uint256 => uint256))))) public heldTokens; uint256 public baseFee; uint256 public stateUpdateFee; uint256 public staminaUpdateFee; uint256 public gasPrice; mapping(uint256 => uint256) public itemFee; uint256 private requestId; bool private autoWithdrawFee; address private treasuryAddress; address public nftStakingPoolAddress; mapping(uint256 => bool) requestWithdrawn; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "MainnetNftBridgePool: caller is not a minter"); _; } modifier onlyOwner() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "MainnetNftBridgePool: caller is not an owner"); _; } function setFees(uint256 _baseFee, uint256 _stateUpdateFee, uint256 _staminaUpdateFee, uint256[] calldata _contractId, uint256[] calldata _itemFee) external onlyOwner { baseFee = _baseFee; stateUpdateFee = _stateUpdateFee; staminaUpdateFee = _staminaUpdateFee; for (uint256 i; i < _contractId.length; i++) { itemFee[_contractId[i]] = _itemFee[i]; } } function setGasPrice(uint256 _gasPrice) external { require(hasRole(MINTER_ROLE, _msgSender()) || hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'no access'); gasPrice = _gasPrice; } function setContracts(uint256[] calldata _contractId, address[] calldata _contractAddress, bool[] calldata _hasSubcontracts) external onlyOwner { for (uint256 i; i < _contractId.length; i++) { nftContracts[_contractId[i]] = _contractAddress[i]; hasSubcontracts[_contractId[i]] = _hasSubcontracts[i]; } } function setDisabledCards(uint256[] calldata _contractId, uint256[] calldata _ids, bool[] calldata _disabled) external onlyOwner { for (uint256 i; i < _ids.length; i++) { cardDisabled[_contractId[i]][_ids[i]] = _disabled[i]; } } function setAutoWithdrawFee(bool _autoWithdrawFee) external onlyOwner { autoWithdrawFee = _autoWithdrawFee; emit AutoWithdrawFeeSet(autoWithdrawFee); } function setTreasuryAddress(address _treasuryAddress) external onlyOwner { treasuryAddress = _treasuryAddress; emit TreasuryAddressSet(_treasuryAddress); } function setNftStakingPoolAddress(address _nftStakingPoolAddress) external onlyOwner { nftStakingPoolAddress = (_nftStakingPoolAddress); } function getSubContractTokenState(address _token, uint256 _cardId, uint256 _tokenId) internal view returns(bytes memory) { (,,,,,,,address subContract) = IRainiCard(_token).cards(_cardId); if (subContract != address(0)) { return IRainiCustomNFT(subContract).getTokenState(_tokenId); } return ''; } function handleFeesWithdraw(uint256 _fee, uint256 _refund) internal { if (_refund > 0) { (bool refundSuccess, ) = _msgSender().call{ value: _refund }(""); require(refundSuccess, "MainnetNftBridgePool: refund transfer failed"); } if (autoWithdrawFee) { (bool withdrawSuccess, ) = treasuryAddress.call{ value: _fee }(""); require(withdrawSuccess, "MainnetNftBridgePool: withdraw transfer failed"); } } function updateSubContractState(address _token, uint256 _cardId, uint256 _tokenId, bytes calldata state) internal { if (state.length == 0) return; (,,,,,,,address subContract) = IRainiCard(_token).cards(_cardId); uint256[] memory ids = new uint256[](1); bytes[] memory states = new bytes[](1); ids[0] = _tokenId; states[0] = state; if (subContract != address(0)) { IRainiCustomNFT(subContract).setTokenStates(ids, states); } } function updateStamina(address _token, uint256 _tokenId, uint32 _stamina) internal { if (_stamina == 0 || nftStakingPoolAddress == address(0)) return; INftStakingPool(nftStakingPoolAddress).setTokenStaminaTotal(_stamina, _tokenId, _token); } struct DepositVars { uint256 fee; uint256 requestId; } function deposit(address _recipient, uint256[] calldata _contractId, uint256[] calldata _tokenIds, uint256[] calldata _amounts) external payable nonReentrant { require(_tokenIds.length == _amounts.length, "MainnetNftBridgePool: input arrays not equal"); DepositVars memory _locals = DepositVars( baseFee, requestId ); for (uint256 i; i < _tokenIds.length; i++) { IRainiCard nftContract = IRainiCard(nftContracts[_contractId[i]]); IRainiCard.TokenVars memory tokenVars = IRainiCard.TokenVars(0,0,0,0); (tokenVars.cardId, tokenVars.level, tokenVars.number, tokenVars.mintedContractChar) = nftContract.tokenVars(_tokenIds[i]); require(!cardDisabled[_contractId[i]][tokenVars.cardId], "MainnetNftBridgePool: bridging this card disabled"); nftContract.safeTransferFrom(_msgSender(), address(this), _tokenIds[i], _amounts[i], ""); setHeldToken(_tokenIds[i], _contractId[i], tokenVars.cardId, tokenVars.level, tokenVars.mintedContractChar, tokenVars.number); _locals.requestId++; _locals.fee += itemFee[_contractId[i]]; bytes memory state = ""; if (tokenVars.number > 0 && hasSubcontracts[_contractId[i]]) { state = getSubContractTokenState(address(nftContract), tokenVars.cardId, _tokenIds[i]); if (state.length > 0) { _locals.fee += stateUpdateFee; } } uint32 stamina = 0; if (nftStakingPoolAddress != address(0)) { stamina = INftStakingPool(nftStakingPoolAddress).getTokenStaminaTotal(_tokenIds[i], address(nftContract)); if (stamina != 0) { _locals.fee += staminaUpdateFee; } } emit CardsDeposited( _contractId[i], _msgSender(), _recipient, _amounts[i], _locals.requestId, tokenVars.cardId, tokenVars.level, tokenVars.number, stamina, tokenVars.mintedContractChar, state ); } _locals.fee *= gasPrice; require(msg.value >= _locals.fee, "MainnetNftBridgePool: not enough funds"); handleFeesWithdraw(_locals.fee, msg.value - _locals.fee); requestId = _locals.requestId; } function getDepositFee(address _recipient, uint256[] calldata _contractId, uint256[] calldata _tokenIds, uint256[] calldata _amounts) public view returns (uint256 fee) { require(_tokenIds.length == _amounts.length, "MainnetNftBridgePool: input arrays not equal"); DepositVars memory _locals = DepositVars( baseFee, requestId ); for (uint256 i; i < _tokenIds.length; i++) { IRainiCard nftContract = IRainiCard(nftContracts[_contractId[i]]); IRainiCard.TokenVars memory tokenVars = IRainiCard.TokenVars(0,0,0,0); (tokenVars.cardId, tokenVars.level, tokenVars.number, tokenVars.mintedContractChar) = nftContract.tokenVars(_tokenIds[i]); require(!cardDisabled[_contractId[i]][tokenVars.cardId], "MainnetNftBridgePool: bridging this card disabled"); _locals.fee += itemFee[_contractId[i]]; bytes memory state = ""; if (tokenVars.number > 0 && hasSubcontracts[_contractId[i]]) { state = getSubContractTokenState(address(nftContract), tokenVars.cardId, _tokenIds[i]); if (state.length > 0) { _locals.fee += stateUpdateFee; } } uint32 stamina = 0; if (nftStakingPoolAddress != address(0)) { INftStakingPool(nftStakingPoolAddress).getTokenStaminaTotal(_tokenIds[i], address(nftContract)); if (stamina != 0) { _locals.fee += staminaUpdateFee; } } } _locals.fee *= gasPrice; return _locals.fee; } function setHeldToken(uint256 tokenId, uint256 _contractId, uint256 _cardId, uint256 _cardLevel, bytes1 _mintedContractChar, uint256 _number) internal { if (_number == 0) { _mintedContractChar = bytes1(0); } if (heldTokens[_contractId][_cardId][_cardLevel][_mintedContractChar][_number] != tokenId) { heldTokens[_contractId][_cardId][_cardLevel][_mintedContractChar][_number] = tokenId; } } function findHeldToken(uint256 _contractId, uint256 _cardId, uint256 _cardLevel, bytes1 _mintedContractChar, uint256 _number) public view returns (uint256) { if (_number == 0) { _mintedContractChar = bytes1(0); } return heldTokens[_contractId][_cardId][_cardLevel][_mintedContractChar][_number]; } struct WithdrawNftVars { uint256 tokenId; uint256 amount; uint256 leftAmount; } function withdrawNft(uint256 _contractId, address _recipient, uint256 _cardId, uint256 _cardLevel, uint256 _amount, bytes1 _mintedContractChar, uint256 _number, uint256 _requestsId, uint32 _stamina, bytes calldata _state) public onlyMinter { if (requestWithdrawn[_requestsId]) { return; } requestWithdrawn[_requestsId] = true; WithdrawNftVars memory _locals = WithdrawNftVars(0, 0, 0); IRainiCard nftContract = IRainiCard(nftContracts[_contractId]); _locals.tokenId = findHeldToken(_contractId, _cardId, _cardLevel, _mintedContractChar, _number); _locals.amount = 0; if (_locals.tokenId > 0) { _locals.amount = nftContract.balanceOf(address(this), _locals.tokenId); } _locals.leftAmount = _amount; if (_locals.amount > 0) { if (_locals.amount > _amount) { _locals.leftAmount = 0; nftContract.safeTransferFrom(address(this), _recipient, _locals.tokenId, _amount, bytes('')); } else { _locals.leftAmount -= _locals.amount; nftContract.safeTransferFrom(address(this), _recipient, _locals.tokenId, _locals.amount, bytes('')); setHeldToken(0, _contractId, _cardId, _cardLevel, _mintedContractChar, _number); } updateStamina(address(nftContract), _locals.tokenId, _stamina); updateSubContractState(address(nftContract), _cardId, _locals.tokenId, _state); } if (_locals.leftAmount > 0) { if (hasSubcontracts[_contractId]) { nftContract.mint(_recipient, _cardId, _cardLevel, _locals.leftAmount, _mintedContractChar, _number, new uint256[](0)); updateSubContractState(address(nftContract), _cardId, nftContract.maxTokenId(), _state); } else { nftContract.mint(_recipient, _cardId, _cardLevel, _locals.leftAmount, _mintedContractChar, _number); } updateStamina(address(nftContract), nftContract.maxTokenId(), _stamina); } emit CardsWithdrawn(_contractId, _recipient, _requestsId, _cardId, _amount); } function bulkWithdrawNfts(uint232[] memory _contractId, address[] memory _recipient, uint256[] memory _cardId, uint256[] memory _cardLevel, uint256[] memory _amount, bytes1[] memory _mintedContractChar, uint256[] memory _number, uint256[] memory _requestsId, uint32[] memory _stamina, bytes[] calldata _state) external onlyMinter { for (uint256 i; i < _contractId.length; i++) { withdrawNft(_contractId[i], _recipient[i], _cardId[i], _cardLevel[i], _amount[i],_mintedContractChar[i], _number[i], _requestsId[i], _stamina[i], _state[i]); } } function withdrawEth(uint256 _amount) external onlyOwner { require(_amount <= address(this).balance, "MainnetNftBridgePool: not enough balance"); (bool success, ) = _msgSender().call{ value: _amount }(""); require(success, "MainnetNftBridgePool: transfer failed"); emit EthWithdrawn(_amount); } function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } function onERC1155Received(address, address, uint256, uint256, bytes calldata) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; interface IRainiCustomNFT { function onTransfered(address from, address to, uint256 id, uint256 amount, bytes memory data) external; function onMerged(uint256 _newTokenId, uint256[] memory _tokenId, address _nftContractAddress, uint256[] memory data) external; function onMinted(address _to, uint256 _tokenId, uint256 _cardId, uint256 _cardLevel, uint256 _amount, bytes1 _mintedContractChar, uint256 _number, uint256[] memory _data) external; function setTokenStates(uint256[] memory id, bytes[] memory state) external; function getTokenState(uint256 id) external view returns (bytes memory); function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; pragma solidity ^0.8.0; abstract contract IRainiCard is IERC1155 { struct TokenVars { uint128 cardId; uint32 level; uint32 number; bytes1 mintedContractChar; } struct Card { uint64 costInUnicorns; uint64 costInRainbows; uint16 maxMintsPerAddress; uint32 maxSupply; // number of base tokens mintable uint32 allocation; // number of base tokens mintable with points on this contract uint32 mintTimeStart; // the timestamp from which the card can be minted bool locked; address subContract; } mapping(uint256 => TokenVars) public tokenVars; mapping(uint256 => Card) public cards; uint256 public maxTokenId; function mint(address _to, uint256 _cardId, uint256 _cardLevel, uint256 _amount, bytes1 _mintedContractChar, uint256 _number, uint256[] memory _data) virtual external; function mint(address _to, uint256 _cardId, uint256 _cardLevel, uint256 _amount, bytes1 _mintedContractChar, uint256 _number) virtual external; function getTotalBalance(address _address) virtual external view returns (uint256[][] memory amounts); function getTotalBalance(address _address, uint256 _cardCount) virtual external view returns (uint256[][] memory amounts); function burn(address _owner, uint256 _tokenId, uint256 _amount) virtual external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
* @dev Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding to learn more about how these ids are created. This function call must use less than 30 000 gas./ SPDX-License-Identifier: MIT* @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 { function mint(address _to, uint256 _cardId, uint256 _cardLevel, uint256 _amount, bytes1 _mintedContractChar, uint256 _number, uint256[] memory _data) virtual external; function mint(address _to, uint256 _cardId, uint256 _cardLevel, uint256 _amount, bytes1 _mintedContractChar, uint256 _number) virtual external; function getTotalBalance(address _address) virtual external view returns (uint256[][] memory amounts); function getTotalBalance(address _address, uint256 _cardCount) virtual external view returns (uint256[][] memory amounts); function burn(address _owner, uint256 _tokenId, uint256 _amount) virtual external; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; import "./IERC165.sol"; function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
12,679,804
[ 1, 1356, 638, 309, 333, 6835, 4792, 326, 1560, 2553, 635, 1375, 5831, 548, 8338, 2164, 326, 4656, 358, 16094, 1898, 2973, 3661, 4259, 3258, 854, 2522, 18, 1220, 445, 745, 1297, 999, 5242, 2353, 5196, 20546, 16189, 18, 19, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 225, 25379, 434, 326, 288, 45, 654, 39, 28275, 97, 1560, 18, 30131, 716, 2545, 358, 2348, 4232, 39, 28275, 1410, 6811, 628, 333, 6835, 471, 3849, 288, 28064, 1358, 97, 358, 866, 364, 326, 3312, 1560, 612, 716, 903, 506, 3260, 18, 2457, 3454, 30, 31621, 30205, 560, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 377, 327, 1560, 548, 422, 618, 12, 12062, 1358, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 289, 31621, 21498, 17526, 16, 288, 654, 39, 28275, 3245, 97, 8121, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 4232, 39, 28275, 353, 467, 654, 39, 28275, 288, 203, 225, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 3327, 548, 16, 2254, 5034, 389, 3327, 2355, 16, 2254, 5034, 389, 8949, 16, 1731, 21, 389, 81, 474, 329, 8924, 2156, 16, 2254, 5034, 389, 2696, 16, 2254, 5034, 8526, 3778, 389, 892, 13, 5024, 3903, 31, 203, 203, 225, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 3327, 548, 16, 2254, 5034, 389, 3327, 2355, 16, 2254, 5034, 389, 8949, 16, 1731, 21, 389, 81, 474, 329, 8924, 2156, 16, 2254, 5034, 389, 2696, 13, 5024, 3903, 31, 203, 203, 225, 445, 12831, 13937, 12, 2867, 389, 2867, 13, 5024, 3903, 1476, 1135, 261, 11890, 5034, 63, 6362, 65, 3778, 30980, 1769, 203, 203, 225, 445, 12831, 13937, 12, 2867, 389, 2867, 16, 2254, 5034, 389, 3327, 1380, 13, 5024, 3903, 1476, 1135, 261, 11890, 5034, 63, 6362, 65, 3778, 30980, 1769, 203, 203, 225, 445, 18305, 12, 2867, 389, 8443, 16, 2254, 5034, 389, 2316, 548, 16, 2254, 5034, 389, 8949, 13, 5024, 3903, 31, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 25165, 45, 654, 39, 28275, 18, 18281, 14432, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 2 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { Token } from "../../token/Token.sol"; import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol"; import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol"; /** * @dev Flash-loan recipient interface */ interface IFlashLoanRecipient { /** * @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee */ function onFlashLoan( address caller, IERC20 erc20Token, uint256 amount, uint256 feeAmount, bytes memory data ) external; } /** * @dev Bancor Network interface */ interface IBancorNetwork is IUpgradeable { /** * @dev returns the set of all valid pool collections */ function poolCollections() external view returns (IPoolCollection[] memory); /** * @dev returns the most recent collection that was added to the pool collections set for a specific type */ function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection); /** * @dev returns the set of all liquidity pools */ function liquidityPools() external view returns (Token[] memory); /** * @dev returns the respective pool collection for the provided pool */ function collectionByPool(Token pool) external view returns (IPoolCollection); /** * @dev returns whether the pool is valid */ function isPoolValid(Token pool) external view returns (bool); /** * @dev creates a new pool * * requirements: * * - the pool doesn't already exist */ function createPool(uint16 poolType, Token token) external; /** * @dev creates new pools * * requirements: * * - none of the pools already exists */ function createPools(uint16 poolType, Token[] calldata tokens) external; /** * @dev migrates a list of pools between pool collections * * notes: * * - invalid or incompatible pools will be skipped gracefully */ function migratePools(Token[] calldata pools) external; /** * @dev deposits liquidity for the specified provider and returns the respective pool token amount * * requirements: * * - the caller must have approved the network to transfer the tokens on its behalf (except for in the * native token case) */ function depositFor( address provider, Token pool, uint256 tokenAmount ) external payable returns (uint256); /** * @dev deposits liquidity for the current provider and returns the respective pool token amount * * requirements: * * - the caller must have approved the network to transfer the tokens on its behalf (except for in the * native token case) */ function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256); /** * @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit * request and returns the respective pool token amount * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function depositForPermitted( address provider, Token pool, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the * respective pool token amount * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function depositPermitted( Token pool, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev initiates liquidity withdrawal * * requirements: * * - the caller must have approved the contract to transfer the pool token amount on its behalf */ function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256); /** * @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function initWithdrawalPermitted( IPoolToken poolToken, uint256 poolTokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev cancels a withdrawal request * * requirements: * * - the caller must have already initiated a withdrawal and received the specified id */ function cancelWithdrawal(uint256 id) external; /** * @dev withdraws liquidity and returns the withdrawn amount * * requirements: * * - the provider must have already initiated a withdrawal and received the specified id * - the specified withdrawal request is eligible for completion * - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT * liquidity */ function withdraw(uint256 id) external returns (uint256); /** * @dev performs a trade by providing the input source amount * * requirements: * * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the * native token case) */ function tradeBySourceAmount( Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary ) external payable; /** * @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an * EIP2612 permit request * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function tradeBySourceAmountPermitted( Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev performs a trade by providing the output target amount * * requirements: * * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the * native token case) */ function tradeByTargetAmount( Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary ) external payable; /** * @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an * EIP2612 permit request and returns the target amount and fee * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function tradeByTargetAmountPermitted( Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev provides a flash-loan * * requirements: * * - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address */ function flashLoan( Token token, uint256 amount, IFlashLoanRecipient recipient, bytes calldata data ) external; /** * @dev deposits liquidity during a migration */ function migrateLiquidity( Token token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount ) external payable; /** * @dev withdraws pending network fees * * requirements: * * - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege */ function withdrawNetworkFees(address recipient) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol"; import { Pool, PoolLiquidity, IPoolCollection, AverageRate } from "./interfaces/IPoolCollection.sol"; import { IPoolToken } from "./interfaces/IPoolToken.sol"; import { IPoolMigrator } from "./interfaces/IPoolMigrator.sol"; import { IVersioned } from "../utility/interfaces/IVersioned.sol"; import { Fraction } from "../utility/FractionLibrary.sol"; import { Upgradeable } from "../utility/Upgradeable.sol"; import { Token } from "../token/Token.sol"; import { Utils, InvalidPool, InvalidPoolCollection } from "../utility/Utils.sol"; interface IPoolCollectionBase { function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external; } interface IPoolCollectionV1 is IPoolCollectionBase { struct PoolLiquidityV1 { uint128 bntTradingLiquidity; // the BNT trading liquidity uint128 baseTokenTradingLiquidity; // the base token trading liquidity uint256 stakedBalance; // the staked balance } struct PoolV1 { IPoolToken poolToken; // the pool token of a given pool uint32 tradingFeePPM; // the trading fee (in units of PPM) bool tradingEnabled; // whether trading is enabled bool depositingEnabled; // whether depositing is enabled AverageRate averageRate; // the recent average rate uint256 depositLimit; // the deposit limit PoolLiquidityV1 liquidity; // the overall liquidity in the pool } function poolData(Token token) external view returns (PoolV1 memory); } /** * @dev Pool Migrator contract */ contract PoolMigrator is IPoolMigrator, Upgradeable, Utils { error UnsupportedVersion(); IPoolCollection private constant INVALID_POOL_COLLECTION = IPoolCollection(address(0)); // the network contract IBancorNetwork private immutable _network; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 0] private __gap; /** * @dev triggered when an existing pool is migrated between pool collections */ event PoolMigrated(Token indexed pool, IPoolCollection prevPoolCollection, IPoolCollection newPoolCollection); /** * @dev a "virtual" constructor that is only used to set immutable state variables */ constructor(IBancorNetwork initNetwork) validAddress(address(initNetwork)) { _network = initNetwork; } /** * @dev fully initializes the contract and its parents */ function initialize() external initializer { __PoolMigrator_init(); } // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __PoolMigrator_init() internal onlyInitializing { __Upgradeable_init(); __PoolMigrator_init_unchained(); } /** * @dev performs contract-specific initialization */ function __PoolMigrator_init_unchained() internal onlyInitializing {} // solhint-enable func-name-mixedcase /** * @inheritdoc Upgradeable */ function version() public pure override(IVersioned, Upgradeable) returns (uint16) { return 1; } /** * @inheritdoc IPoolMigrator */ function migratePool(Token pool) external only(address(_network)) returns (IPoolCollection) { if (address(pool) == address(0)) { revert InvalidPool(); } // get the pool collection that this pool exists in IPoolCollection prevPoolCollection = _network.collectionByPool(pool); if (address(prevPoolCollection) == address(0)) { revert InvalidPool(); } // get the latest pool collection corresponding to its type and ensure that a migration is necessary // note that it's currently not possible to add two pool collections with the same version or type uint16 poolType = prevPoolCollection.poolType(); IPoolCollection newPoolCollection = _network.latestPoolCollection(poolType); if (address(newPoolCollection) == address(prevPoolCollection)) { revert InvalidPoolCollection(); } // migrate all relevant values based on a historical collection version into the new pool collection if (prevPoolCollection.version() == 1) { _migrateFromV1(pool, IPoolCollectionV1(address(prevPoolCollection)), newPoolCollection); emit PoolMigrated({ pool: pool, prevPoolCollection: prevPoolCollection, newPoolCollection: newPoolCollection }); return newPoolCollection; } revert UnsupportedVersion(); } /** * @dev migrates a V1 pool to the latest pool version */ function _migrateFromV1( Token pool, IPoolCollectionV1 sourcePoolCollection, IPoolCollection targetPoolCollection ) private { IPoolCollectionV1.PoolV1 memory data = sourcePoolCollection.poolData(pool); // since the latest pool collection is also v1, currently not additional pre- or post-processing is needed Pool memory newData = Pool({ poolToken: data.poolToken, tradingFeePPM: data.tradingFeePPM, tradingEnabled: data.tradingEnabled, depositingEnabled: data.depositingEnabled, averageRate: data.averageRate, depositLimit: data.depositLimit, liquidity: PoolLiquidity({ bntTradingLiquidity: data.liquidity.bntTradingLiquidity, baseTokenTradingLiquidity: data.liquidity.baseTokenTradingLiquidity, stakedBalance: data.liquidity.stakedBalance }) }); sourcePoolCollection.migratePoolOut(pool, targetPoolCollection); targetPoolCollection.migratePoolIn(pool, newData); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { Fraction112 } from "../../utility/FractionLibrary.sol"; import { Token } from "../../token/Token.sol"; import { IPoolToken } from "./IPoolToken.sol"; struct PoolLiquidity { uint128 bntTradingLiquidity; // the BNT trading liquidity uint128 baseTokenTradingLiquidity; // the base token trading liquidity uint256 stakedBalance; // the staked balance } struct AverageRate { uint32 blockNumber; Fraction112 rate; } struct Pool { IPoolToken poolToken; // the pool token of the pool uint32 tradingFeePPM; // the trading fee (in units of PPM) bool tradingEnabled; // whether trading is enabled bool depositingEnabled; // whether depositing is enabled AverageRate averageRate; // the recent average rate uint256 depositLimit; // the deposit limit PoolLiquidity liquidity; // the overall liquidity in the pool } struct WithdrawalAmounts { uint256 totalAmount; uint256 baseTokenAmount; uint256 bntAmount; } // trading enabling/disabling reasons uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0; uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1; uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2; struct TradeAmountAndFee { uint256 amount; // the source/target amount (depending on the context) resulting from the trade uint256 tradingFeeAmount; // the trading fee amount uint256 networkFeeAmount; // the network fee amount (always in units of BNT) } /** * @dev Pool Collection interface */ interface IPoolCollection is IVersioned { /** * @dev returns the type of the pool */ function poolType() external pure returns (uint16); /** * @dev returns the default trading fee (in units of PPM) */ function defaultTradingFeePPM() external view returns (uint32); /** * @dev returns all the pools which are managed by this pool collection */ function pools() external view returns (Token[] memory); /** * @dev returns the number of all the pools which are managed by this pool collection */ function poolCount() external view returns (uint256); /** * @dev returns whether a pool is valid */ function isPoolValid(Token pool) external view returns (bool); /** * @dev returns specific pool's data */ function poolData(Token pool) external view returns (Pool memory); /** * @dev returns the overall liquidity in the pool */ function poolLiquidity(Token pool) external view returns (PoolLiquidity memory); /** * @dev returns the pool token of the pool */ function poolToken(Token pool) external view returns (IPoolToken); /** * @dev converts the specified pool token amount to the underlying base token amount */ function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256); /** * @dev converts the specified underlying base token amount to pool token amount */ function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256); /** * @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified * amount */ function poolTokenAmountToBurn( Token pool, uint256 tokenAmountToDistribute, uint256 protocolPoolTokenAmount ) external view returns (uint256); /** * @dev creates a new pool * * requirements: * * - the caller must be the network contract * - the pool should have been whitelisted * - the pool isn't already defined in the collection */ function createPool(Token token) external; /** * @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount * * requirements: * * - the caller must be the network contract * - assumes that the base token has been already deposited in the vault */ function depositFor( bytes32 contextId, address provider, Token pool, uint256 tokenAmount ) external returns (uint256); /** * @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount * * requirements: * * - the caller must be the network contract * - the caller must have approved the collection to transfer/burn the pool token amount on its behalf */ function withdraw( bytes32 contextId, address provider, Token pool, uint256 poolTokenAmount ) external returns (uint256); /** * @dev returns the amounts that would be returned if the position is currently withdrawn, * along with the breakdown of the base token and the BNT compensation */ function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory); /** * @dev performs a trade by providing the source amount and returns the target amount and the associated fee * * requirements: * * - the caller must be the network contract */ function tradeBySourceAmount( bytes32 contextId, Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount ) external returns (TradeAmountAndFee memory); /** * @dev performs a trade by providing the target amount and returns the required source amount and the associated fee * * requirements: * * - the caller must be the network contract */ function tradeByTargetAmount( bytes32 contextId, Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount ) external returns (TradeAmountAndFee memory); /** * @dev returns the output amount and fee when trading by providing the source amount */ function tradeOutputAndFeeBySourceAmount( Token sourceToken, Token targetToken, uint256 sourceAmount ) external view returns (TradeAmountAndFee memory); /** * @dev returns the input amount and fee when trading by providing the target amount */ function tradeInputAndFeeByTargetAmount( Token sourceToken, Token targetToken, uint256 targetAmount ) external view returns (TradeAmountAndFee memory); /** * @dev notifies the pool of accrued fees * * requirements: * * - the caller must be the network contract */ function onFeesCollected(Token pool, uint256 feeAmount) external; /** * @dev migrates a pool to this pool collection * * requirements: * * - the caller must be the pool migrator contract */ function migratePoolIn(Token pool, Pool calldata data) external; /** * @dev migrates a pool from this pool collection * * requirements: * * - the caller must be the pool migrator contract */ function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Token } from "../../token/Token.sol"; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { IPoolCollection } from "./IPoolCollection.sol"; /** * @dev Pool Migrator interface */ interface IPoolMigrator is IVersioned { /** * @dev migrates a pool and returns the new pool collection it exists in * * notes: * * - invalid or incompatible pools will be skipped gracefully * * requirements: * * - the caller must be the network contract */ function migratePool(Token pool) external returns (IPoolCollection); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol"; import { Token } from "../../token/Token.sol"; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { IOwned } from "../../utility/interfaces/IOwned.sol"; /** * @dev Pool Token interface */ interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable { /** * @dev returns the address of the reserve token */ function reserveToken() external view returns (Token); /** * @dev increases the token supply and sends the new tokens to the given account * * requirements: * * - the caller must be the owner of the contract */ function mint(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions, * but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract */ interface Token { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev burnable ERC20 interface */ interface IERC20Burnable { /** * @dev Destroys tokens from the caller. */ function burn(uint256 amount) external; /** * @dev Destroys tokens from a recipient, deducting from the caller's allowance * * requirements: * * - the caller must have allowance for recipient's tokens of at least the specified amount */ function burnFrom(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; uint32 constant PPM_RESOLUTION = 1000000; // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; struct Fraction { uint256 n; uint256 d; } struct Fraction112 { uint112 n; uint112 d; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Fraction, Fraction112 } from "./Fraction.sol"; import { MathEx } from "./MathEx.sol"; // solhint-disable-next-line func-visibility function zeroFraction() pure returns (Fraction memory) { return Fraction({ n: 0, d: 1 }); } // solhint-disable-next-line func-visibility function zeroFraction112() pure returns (Fraction112 memory) { return Fraction112({ n: 0, d: 1 }); } /** * @dev this library provides a set of fraction operations */ library FractionLibrary { /** * @dev returns whether a standard fraction is valid */ function isValid(Fraction memory fraction) internal pure returns (bool) { return fraction.d != 0; } /** * @dev returns whether a standard fraction is positive */ function isPositive(Fraction memory fraction) internal pure returns (bool) { return isValid(fraction) && fraction.n != 0; } /** * @dev returns whether a 112-bit fraction is valid */ function isValid(Fraction112 memory fraction) internal pure returns (bool) { return fraction.d != 0; } /** * @dev returns whether a 112-bit fraction is positive */ function isPositive(Fraction112 memory fraction) internal pure returns (bool) { return isValid(fraction) && fraction.n != 0; } /** * @dev reduces a standard fraction to a 112-bit fraction */ function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) { Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max); return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) }); } /** * @dev expands a 112-bit fraction to a standard fraction */ function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) { return Fraction({ n: fraction.n, d: fraction.d }); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { Fraction } from "./Fraction.sol"; import { PPM_RESOLUTION } from "./Constants.sol"; uint256 constant ONE = 1 << 127; struct Uint512 { uint256 hi; // 256 most significant bits uint256 lo; // 256 least significant bits } struct Sint256 { uint256 value; bool isNeg; } /** * @dev this library provides a set of complex math operations */ library MathEx { error Overflow(); /** * @dev returns `e ^ f`, where `e` is Euler's number and `f` is the input exponent: * - 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 exp(Fraction memory f) internal pure returns (Fraction memory) { uint256 x = MathEx.mulDivF(ONE, f.n, f.d); uint256 y; uint256 z; uint256 n; if (x >= (ONE << 4)) { revert Overflow(); } unchecked { z = y = x % (ONE >> 3); // get the input modulo 2^(-3) z = (z * y) / ONE; n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / ONE; n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / ONE; n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / ONE; n += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / ONE; n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / ONE; n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / ONE; n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / ONE; n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / ONE; n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / ONE; n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / ONE; n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / ONE; n += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / ONE; n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / ONE; n += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / ONE; n += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / ONE; n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / ONE; n += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / ONE; n += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / ONE; n += z * 0x0000000000000001; // add y^20 * (20! / 20!) n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & (ONE >> 3)) != 0) n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & (ONE >> 2)) != 0) n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & (ONE >> 1)) != 0) n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & (ONE << 0)) != 0) n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & (ONE << 1)) != 0) n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & (ONE << 2)) != 0) n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & (ONE << 3)) != 0) n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) } return Fraction({ n: n, d: ONE }); } /** * @dev returns a fraction with reduced components */ function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) { uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max); return Fraction({ n: fraction.n / scale, d: fraction.d / scale }); } /** * @dev returns the weighted average of two fractions */ function weightedAverage( Fraction memory fraction1, Fraction memory fraction2, uint256 weight1, uint256 weight2 ) internal pure returns (Fraction memory) { return Fraction({ n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2, d: fraction1.d * fraction2.d * (weight1 + weight2) }); } /** * @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range * for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base` */ function isInRange( Fraction memory baseSample, Fraction memory offsetSample, uint32 maxDeviationPPM ) internal pure returns (bool) { Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM)); Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION); Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM)); return lte512(min, mid) && lte512(mid, max); } /** * @dev returns an `Sint256` positive representation of an unsigned integer */ function toPos256(uint256 n) internal pure returns (Sint256 memory) { return Sint256({ value: n, isNeg: false }); } /** * @dev returns an `Sint256` negative representation of an unsigned integer */ function toNeg256(uint256 n) internal pure returns (Sint256 memory) { return Sint256({ value: n, isNeg: true }); } /** * @dev returns the largest integer smaller than or equal to `x * y / z` */ function mulDivF( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256) { Uint512 memory xy = mul512(x, y); // if `x * y < 2 ^ 256` if (xy.hi == 0) { return xy.lo / z; } // assert `x * y / z < 2 ^ 256` if (xy.hi >= z) { revert Overflow(); } uint256 m = _mulMod(x, y, z); // `m = x * y % z` Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)` // if `n < 2 ^ 256` if (n.hi == 0) { return n.lo / z; } uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p` uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256` return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z` } /** * @dev returns the smallest integer larger than or equal to `x * y / z` */ function mulDivC( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256) { uint256 w = mulDivF(x, y, z); if (_mulMod(x, y, z) > 0) { if (w >= type(uint256).max) { revert Overflow(); } return w + 1; } return w; } /** * @dev returns the maximum of `n1 - n2` and 0 */ function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) { return n1 > n2 ? n1 - n2 : 0; } /** * @dev returns the value of `x > y` */ function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo); } /** * @dev returns the value of `x < y` */ function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo); } /** * @dev returns the value of `x >= y` */ function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return !lt512(x, y); } /** * @dev returns the value of `x <= y` */ function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return !gt512(x, y); } /** * @dev returns the value of `x * y` */ function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) { uint256 p = _mulModMax(x, y); uint256 q = _unsafeMul(x, y); if (p >= q) { return Uint512({ hi: p - q, lo: q }); } return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q }); } /** * @dev returns the value of `x - y`, given that `x >= y` */ function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) { if (x.lo >= y) { return Uint512({ hi: x.hi, lo: x.lo - y }); } return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) }); } /** * @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n` */ function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) { uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)` return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)` } /** * @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2` */ function _inv256(uint256 d) private pure returns (uint256) { // approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method uint256 x = 1; for (uint256 i = 0; i < 8; i++) { x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256` } return x; } /** * @dev returns `(x + y) % 2 ^ 256` */ function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x + y; } } /** * @dev returns `(x - y) % 2 ^ 256` */ function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x - y; } } /** * @dev returns `(x * y) % 2 ^ 256` */ function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x * y; } } /** * @dev returns `x * y % (2 ^ 256 - 1)` */ function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) { return mulmod(x, y, type(uint256).max); } /** * @dev returns `x * y % z` */ function _mulMod( uint256 x, uint256 y, uint256 z ) private pure returns (uint256) { return mulmod(x, y, z); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import { IUpgradeable } from "./interfaces/IUpgradeable.sol"; import { AccessDenied } from "./Utils.sol"; /** * @dev this contract provides common utilities for upgradeable contracts */ abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable { error AlreadyInitialized(); // the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract // upgrades bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); uint32 internal constant MAX_GAP = 50; uint16 internal _initializations; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 1] private __gap; // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __Upgradeable_init() internal onlyInitializing { __AccessControl_init(); __Upgradeable_init_unchained(); } /** * @dev performs contract-specific initialization */ function __Upgradeable_init_unchained() internal onlyInitializing { _initializations = 1; // set up administrative roles _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); // allow the deployer to initially be the admin of the contract _setupRole(ROLE_ADMIN, msg.sender); } // solhint-enable func-name-mixedcase modifier onlyAdmin() { _hasRole(ROLE_ADMIN, msg.sender); _; } modifier onlyRoleMember(bytes32 role) { _hasRole(role, msg.sender); _; } function version() public view virtual override returns (uint16); /** * @dev returns the admin role */ function roleAdmin() external pure returns (bytes32) { return ROLE_ADMIN; } /** * @dev performs post-upgrade initialization * * requirements: * * - this must can be called only once per-upgrade */ function postUpgrade(bytes calldata data) external { uint16 initializations = _initializations + 1; if (initializations != version()) { revert AlreadyInitialized(); } _initializations = initializations; _postUpgrade(data); } /** * @dev an optional post-upgrade callback that can be implemented by child contracts */ function _postUpgrade( bytes calldata /* data */ ) internal virtual {} function _hasRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert AccessDenied(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { PPM_RESOLUTION } from "./Constants.sol"; error AccessDenied(); error AlreadyExists(); error DoesNotExist(); error InvalidAddress(); error InvalidExternalAddress(); error InvalidFee(); error InvalidPool(); error InvalidPoolCollection(); error InvalidStakedBalance(); error InvalidToken(); error InvalidType(); error InvalidParam(); error NotEmpty(); error NotPayable(); error ZeroValue(); /** * @dev common utilities */ contract Utils { // allows execution by the caller only modifier only(address caller) { _only(caller); _; } function _only(address caller) internal view { if (msg.sender != caller) { revert AccessDenied(); } } // verifies that a value is greater than zero modifier greaterThanZero(uint256 value) { _greaterThanZero(value); _; } // error message binary size optimization function _greaterThanZero(uint256 value) internal pure { if (value == 0) { revert ZeroValue(); } } // validates an address - currently only checks that it isn't null modifier validAddress(address addr) { _validAddress(addr); _; } // error message binary size optimization function _validAddress(address addr) internal pure { if (addr == address(0)) { revert InvalidAddress(); } } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address addr) { _validExternalAddress(addr); _; } // error message binary size optimization function _validExternalAddress(address addr) internal view { if (addr == address(0) || addr == address(this)) { revert InvalidExternalAddress(); } } // ensures that the fee is valid modifier validFee(uint32 fee) { _validFee(fee); _; } // error message binary size optimization function _validFee(uint32 fee) internal pure { if (fee > PPM_RESOLUTION) { revert InvalidFee(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev Owned interface */ interface IOwned { /** * @dev returns the address of the current owner */ function owner() external view returns (address); /** * @dev allows transferring the contract ownership * * requirements: * * - the caller must be the owner of the contract * - the new owner still needs to accept the transfer */ function transferOwnership(address ownerCandidate) external; /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "./IVersioned.sol"; import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol"; /** * @dev this is the common interface for upgradeable contracts */ interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev an interface for a versioned contract */ interface IVersioned { function version() external view returns (uint16); }
whether depositing is enabled
bool depositingEnabled;
5,985,700
[ 1, 3350, 2437, 443, 1724, 310, 353, 3696, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1426, 443, 1724, 310, 1526, 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 ]
./full_match/1/0x27a7296A9d282E55Bdf7Ac3A7B768763dD65dE1E/sources/contracts/DutchAuction.sol
* @notice Checks how much is user able to commit and processes that commitment. @dev Users must approve contract prior to committing tokens to auction. @param _from User ERC20 address. @param _amount Amount of approved ERC20 tokens./
function commitTokensFrom( address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement ) public nonReentrant { require(address(paymentCurrency) != ETH_ADDRESS, "DutchAuction: Payment currency is not a token"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } uint256 tokensToTransfer = calculateCommitment(_amount); if (tokensToTransfer > 0) { _safeTransferFrom(paymentCurrency, msg.sender, tokensToTransfer); _addCommitment(_from, tokensToTransfer); } }
3,869,948
[ 1, 4081, 3661, 9816, 353, 729, 7752, 358, 3294, 471, 8488, 716, 23274, 18, 225, 12109, 1297, 6617, 537, 6835, 6432, 358, 3294, 1787, 2430, 358, 279, 4062, 18, 225, 389, 2080, 2177, 4232, 39, 3462, 1758, 18, 225, 389, 8949, 16811, 434, 20412, 4232, 39, 3462, 2430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3294, 5157, 1265, 12, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1426, 855, 1876, 2577, 15656, 774, 3882, 278, 1988, 24629, 367, 17420, 203, 565, 262, 203, 3639, 1071, 282, 1661, 426, 8230, 970, 21281, 565, 288, 203, 3639, 2583, 12, 2867, 12, 9261, 7623, 13, 480, 512, 2455, 67, 15140, 16, 315, 40, 322, 343, 37, 4062, 30, 12022, 5462, 353, 486, 279, 1147, 8863, 203, 3639, 309, 12, 896, 1876, 2577, 15656, 774, 3882, 278, 1988, 24629, 367, 17420, 422, 629, 13, 288, 203, 5411, 15226, 38, 11884, 1299, 18250, 1248, 20632, 17420, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 2430, 774, 5912, 273, 4604, 5580, 475, 24899, 8949, 1769, 203, 3639, 309, 261, 7860, 774, 5912, 405, 374, 13, 288, 203, 5411, 389, 4626, 5912, 1265, 12, 9261, 7623, 16, 1234, 18, 15330, 16, 2430, 774, 5912, 1769, 203, 5411, 389, 1289, 5580, 475, 24899, 2080, 16, 2430, 774, 5912, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x4FE73e57343931E713728d5dc334F7298666E980/sources/contracts/ITruthPost.sol
@title The Truth Post: Accurate and Relevant News @author https://github.com/proveuswrong<0xferit, gratestas> @dev This contract serves as a standard interface among multiple deployments of the Truth Post contracts. You should target this interface contract for interactions, not the concrete contract; otherwise you risk incompatibility across versions. @custom:approvals 0xferit, gratestas
abstract contract ITruthPost { string public constant VERSION = "1.2.0"; enum RulingOptions { Tied, ChallengeFailed, Debunked } bool isPublishingEnabled = true; address payable public TREASURY; uint256 public treasuryBalance; uint256 public constant NUMBER_OF_RULING_OPTIONS = 2; uint256 public challengeTaxRate = 16; constructor( uint256 _articleWithdrawalTimelock, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier, address payable _treasury ) { ARTICLE_WITHDRAWAL_TIMELOCK = _articleWithdrawalTimelock; WINNER_STAKE_MULTIPLIER = _winnerStakeMultiplier; LOSER_STAKE_MULTIPLIER = _loserStakeMultiplier; TREASURY = _treasury; } event NewArticle(string articleID, uint8 category, uint256 articleAddress); event Debunked(uint256 articleAddress); event ArticleWithdrawn(uint256 articleAddress); event BalanceUpdate(uint256 articleAddress, uint256 newTotal); event TimelockStarted(uint256 articleAddress); event Challenge(uint256 indexed articleAddress, address challanger, uint256 disputeID); event Contribution( uint256 indexed disputeId, uint256 indexed round, RulingOptions ruling, address indexed contributor, uint256 amount ); event Withdrawal( uint256 indexed disputeId, uint256 indexed round, RulingOptions ruling, address indexed contributor, uint256 reward ); event RulingFunded(uint256 indexed disputeId, uint256 indexed round, RulingOptions indexed ruling); }
11,588,974
[ 1, 1986, 840, 795, 5616, 30, 432, 2803, 340, 471, 4275, 73, 7445, 27061, 225, 2333, 2207, 6662, 18, 832, 19, 685, 537, 407, 21530, 32, 20, 23168, 305, 16, 3821, 270, 395, 345, 34, 377, 1220, 6835, 26255, 487, 279, 4529, 1560, 17200, 3229, 20422, 434, 326, 840, 795, 5616, 20092, 18, 540, 4554, 1410, 1018, 333, 1560, 6835, 364, 23877, 16, 486, 326, 12220, 6835, 31, 3541, 1846, 18404, 316, 27303, 10279, 5244, 18, 632, 3662, 30, 12908, 4524, 374, 23168, 305, 16, 3821, 270, 395, 345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1070, 795, 3349, 288, 203, 565, 533, 1071, 5381, 8456, 273, 315, 21, 18, 22, 18, 20, 14432, 203, 203, 203, 565, 2792, 534, 332, 310, 1320, 288, 203, 3639, 399, 2092, 16, 203, 3639, 1680, 8525, 2925, 16, 203, 3639, 1505, 70, 1683, 329, 203, 565, 289, 203, 203, 565, 1426, 353, 6024, 310, 1526, 273, 638, 31, 203, 565, 1758, 8843, 429, 1071, 399, 862, 3033, 1099, 61, 31, 203, 565, 2254, 5034, 1071, 9787, 345, 22498, 13937, 31, 203, 565, 2254, 5034, 1071, 5381, 15532, 67, 3932, 67, 54, 1506, 1360, 67, 12422, 273, 576, 31, 203, 565, 2254, 5034, 1071, 12948, 7731, 4727, 273, 2872, 31, 203, 203, 565, 3885, 12, 203, 3639, 2254, 5034, 389, 11480, 1190, 9446, 287, 10178, 292, 975, 16, 203, 3639, 2254, 5034, 389, 91, 7872, 510, 911, 23365, 16, 203, 3639, 2254, 5034, 389, 383, 550, 510, 911, 23365, 16, 203, 3639, 1758, 8843, 429, 389, 27427, 345, 22498, 203, 565, 262, 288, 203, 3639, 6052, 56, 2871, 900, 67, 9147, 40, 10821, 1013, 67, 4684, 6589, 273, 389, 11480, 1190, 9446, 287, 10178, 292, 975, 31, 203, 3639, 678, 25000, 67, 882, 37, 6859, 67, 24683, 2053, 654, 273, 389, 91, 7872, 510, 911, 23365, 31, 203, 3639, 1806, 2123, 67, 882, 37, 6859, 67, 24683, 2053, 654, 273, 389, 383, 550, 510, 911, 23365, 31, 203, 3639, 399, 862, 3033, 1099, 61, 273, 389, 27427, 345, 22498, 31, 203, 565, 289, 203, 203, 565, 871, 1166, 7880, 12, 1080, 2 ]
./partial_match/1/0x8661422Dd4464147975056a9139959b4B1C2bcc3/sources/DFDRewardsTest.sol
Deduct the remaining from balance
_balances[msg.sender] = _balances[msg.sender].sub(amount.sub(release));
4,016,673
[ 1, 20563, 853, 326, 4463, 628, 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, 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, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 70, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 8949, 18, 1717, 12, 9340, 10019, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.15; contract IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns(bool); } contract IQueryableFactRegistry is IFactRegistry { /* Returns true if at least one fact has been registered. */ function hasRegisteredFact() external view returns(bool); } contract Identity { /* Allows a caller, typically another contract, to ensure that the provided address is of the expected type and version. */ function identify() external pure returns(string memory); } contract FactRegistry is IQueryableFactRegistry { // Mapping: fact hash -> true. mapping (bytes32 => bool) private verifiedFact; // Indicates whether the Fact Registry has at least one fact registered. bool anyFactRegistered; /* Checks if a fact has been verified. */ function isValid(bytes32 fact) external view returns(bool) { return _factCheck(fact); } /* This is an internal method to check if the fact is already registered. In current implementation of FactRegistry it's identical to isValid(). But the check is against the local fact registry, So for a derived referral fact registry, it's not the same. */ function _factCheck(bytes32 fact) internal view returns(bool) { return verifiedFact[fact]; } function registerFact( bytes32 factHash ) internal { // This function stores the fact hash in the mapping. verifiedFact[factHash] = true; // Mark first time off. if (!anyFactRegistered) { anyFactRegistered = true; } } /* Indicates whether at least one fact was registered. */ function hasRegisteredFact() external view returns(bool) { return anyFactRegistered; } } contract Committee is FactRegistry, Identity { uint256 constant SIGNATURE_LENGTH = 32 * 2 + 1; // r(32) + s(32) + v(1). uint256 public signaturesRequired; mapping (address => bool) public isMember; /// @dev Contract constructor sets initial members and required number of signatures. /// @param committeeMembers List of committee members. /// @param numSignaturesRequired Number of required signatures. constructor (address[] memory committeeMembers, uint256 numSignaturesRequired) public { require(numSignaturesRequired <= committeeMembers.length, "TOO_MANY_REQUIRED_SIGNATURES"); for (uint256 idx = 0; idx < committeeMembers.length; idx++) { require(!isMember[committeeMembers[idx]], "NON_UNIQUE_COMMITTEE_MEMBERS"); isMember[committeeMembers[idx]] = true; } signaturesRequired = numSignaturesRequired; } function identify() external pure returns(string memory) { return "StarkWare_Committee_2019_1"; } /// @dev Verifies the availability proof. Reverts if invalid. /// An availability proof should have a form of a concatenation of ec-signatures by signatories. /// Signatures should be sorted by signatory address ascendingly. /// Signatures should be 65 bytes long. r(32) + s(32) + v(1). /// There should be at least the number of required signatures as defined in this contract /// and all signatures provided should be from signatories. /// /// See :sol:mod:`AvailabilityVerifiers` for more information on when this is used. /// /// @param claimHash The hash of the claim the committee is signing on. /// The format is keccak256(abi.encodePacked( /// newVaultRoot, vaultTreeHeight, newOrderRoot, orderTreeHeight sequenceNumber)) /// @param availabilityProofs Concatenated ec signatures by committee members. function verifyAvailabilityProof( bytes32 claimHash, bytes calldata availabilityProofs ) external { require( availabilityProofs.length >= signaturesRequired * SIGNATURE_LENGTH, "INVALID_AVAILABILITY_PROOF_LENGTH"); uint256 offset = 0; address prevRecoveredAddress = address(0); for (uint256 proofIdx = 0; proofIdx < signaturesRequired; proofIdx++) { bytes32 r = bytesToBytes32(availabilityProofs, offset); bytes32 s = bytesToBytes32(availabilityProofs, offset + 32); uint8 v = uint8(availabilityProofs[offset + 64]); offset += SIGNATURE_LENGTH; address recovered = ecrecover( claimHash, v, r, s ); // Signatures should be sorted off-chain before submitting to enable cheap uniqueness // check on-chain. require(isMember[recovered], "AVAILABILITY_PROVER_NOT_IN_COMMITTEE"); require(recovered > prevRecoveredAddress, "NON_SORTED_SIGNATURES"); prevRecoveredAddress = recovered; } registerFact(claimHash); } function bytesToBytes32(bytes memory array, uint256 offset) private pure returns (bytes32 result) { // Arrays are prefixed by a 256 bit length parameter. uint256 actualOffset = offset + 32; // Read the bytes32 from array memory. // solium-disable-next-line security/no-inline-assembly assembly { result := mload(add(array, actualOffset)) } } }
@dev Contract constructor sets initial members and required number of signatures. @param committeeMembers List of committee members. @param numSignaturesRequired Number of required signatures.
{ require(numSignaturesRequired <= committeeMembers.length, "TOO_MANY_REQUIRED_SIGNATURES"); for (uint256 idx = 0; idx < committeeMembers.length; idx++) { require(!isMember[committeeMembers[idx]], "NON_UNIQUE_COMMITTEE_MEMBERS"); isMember[committeeMembers[idx]] = true; } signaturesRequired = numSignaturesRequired; }
7,377,256
[ 1, 8924, 3885, 1678, 2172, 4833, 471, 1931, 1300, 434, 14862, 18, 225, 3294, 22579, 6918, 987, 434, 3294, 22579, 4833, 18, 225, 818, 23918, 3705, 3588, 434, 1931, 14862, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 203, 3639, 2583, 12, 2107, 23918, 3705, 1648, 3294, 22579, 6918, 18, 2469, 16, 315, 4296, 51, 67, 24177, 67, 14977, 67, 26587, 55, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 2067, 273, 374, 31, 2067, 411, 3294, 22579, 6918, 18, 2469, 31, 2067, 27245, 288, 203, 203, 5411, 2583, 12, 5, 291, 4419, 63, 7371, 22579, 6918, 63, 3465, 65, 6487, 315, 3993, 67, 16879, 67, 18658, 1448, 41, 67, 19630, 55, 8863, 203, 203, 5411, 353, 4419, 63, 7371, 22579, 6918, 63, 3465, 13563, 273, 638, 31, 203, 203, 3639, 289, 203, 203, 3639, 14862, 3705, 273, 818, 23918, 3705, 31, 203, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x313df3fac623a824c8e64b4c47cf62fe0b75809e //Contract name: Whitelist //Balance: 0 Ether //Verification Date: 2/26/2018 //Transacion Count: 5 // CODE STARTS HERE pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/examples/SimpleToken.sol /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract SimpleToken is StandardToken { string public constant name = "SimpleToken"; // solium-disable-line uppercase string public constant symbol = "SIM"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ function SimpleToken() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/LockedOutTokens.sol // for unit test purposes only contract LockedOutTokens is Ownable { address public wallet; uint8 public tranchesCount; uint256 public trancheSize; uint256 public period; uint256 public startTimestamp; uint8 public tranchesPayedOut = 0; ERC20Basic internal token; function LockedOutTokens( address _wallet, address _tokenAddress, uint256 _startTimestamp, uint8 _tranchesCount, uint256 _trancheSize, uint256 _periodSeconds ) { require(_wallet != address(0)); require(_tokenAddress != address(0)); require(_startTimestamp > 0); require(_tranchesCount > 0); require(_trancheSize > 0); require(_periodSeconds > 0); wallet = _wallet; tranchesCount = _tranchesCount; startTimestamp = _startTimestamp; trancheSize = _trancheSize; period = _periodSeconds; token = ERC20Basic(_tokenAddress); } function grant() public { require(wallet == msg.sender); require(tranchesPayedOut < tranchesCount); require(startTimestamp > 0); require(now >= startTimestamp + (period * (tranchesPayedOut + 1))); tranchesPayedOut = tranchesPayedOut + 1; token.transfer(wallet, trancheSize); } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: contracts/TiqpitToken.sol contract TiqpitToken is StandardToken, Pausable { using SafeMath for uint256; string constant public name = "Tiqpit Token"; string constant public symbol = "PIT"; uint8 constant public decimals = 18; string constant public smallestUnitName = "TIQ"; uint256 constant public INITIAL_TOTAL_SUPPLY = 500e6 * (uint256(10) ** decimals); address private addressIco; modifier onlyIco() { require(msg.sender == addressIco); _; } /** * @dev Create TiqpitToken contract and set pause * @param _ico The address of ICO contract. */ function TiqpitToken (address _ico) public { require(_ico != address(0)); addressIco = _ico; totalSupply_ = totalSupply_.add(INITIAL_TOTAL_SUPPLY); balances[_ico] = balances[_ico].add(INITIAL_TOTAL_SUPPLY); Transfer(address(0), _ico, INITIAL_TOTAL_SUPPLY); pause(); } /** * @dev Transfer token for a specified address with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @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) whenNotPaused public returns (bool) { super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens from ICO address to another address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) { super.transfer(_to, _value); } /** * @dev Burn a specific amount of tokens of other token holders if refund process enable. * @param _from The address of token holder whose tokens to be burned. */ function burnFromAddress(address _from) onlyIco public { uint256 amount = balances[_from]; require(_from != address(0)); require(amount > 0); require(amount <= balances[_from]); balances[_from] = balances[_from].sub(amount); totalSupply_ = totalSupply_.sub(amount); Transfer(_from, address(0), amount); } } // File: contracts/Whitelist.sol /** * @title Whitelist contract * @dev Whitelist for wallets. */ contract Whitelist is Ownable { mapping(address => bool) whitelist; uint256 public whitelistLength = 0; address public backendAddress; /** * @dev Add wallet to whitelist. * @dev Accept request from the owner only. * @param _wallet The address of wallet to add. */ function addWallet(address _wallet) public onlyPrivilegedAddresses { require(_wallet != address(0)); require(!isWhitelisted(_wallet)); whitelist[_wallet] = true; whitelistLength++; } /** * @dev Remove wallet from whitelist. * @dev Accept request from the owner only. * @param _wallet The address of whitelisted wallet to remove. */ function removeWallet(address _wallet) public onlyOwner { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet] = false; whitelistLength--; } /** * @dev Check the specified wallet whether it is in the whitelist. * @param _wallet The address of wallet to check. */ function isWhitelisted(address _wallet) constant public returns (bool) { return whitelist[_wallet]; } /** * @dev Sets the backend address for automated operations. * @param _backendAddress The backend address to allow. */ function setBackendAddress(address _backendAddress) public onlyOwner { require(_backendAddress != address(0)); backendAddress = _backendAddress; } /** * @dev Allows the function to be called only by the owner and backend. */ modifier onlyPrivilegedAddresses() { require(msg.sender == owner || msg.sender == backendAddress); _; } } // File: contracts/Whitelistable.sol contract Whitelistable { Whitelist public whitelist; modifier whenWhitelisted(address _wallet) { require(whitelist.isWhitelisted(_wallet)); _; } /** * @dev Constructor for Whitelistable contract. */ function Whitelistable() public { whitelist = new Whitelist(); } } // File: contracts/TiqpitCrowdsale.sol contract TiqpitCrowdsale is Pausable, Whitelistable { using SafeMath for uint256; uint256 constant private DECIMALS = 18; uint256 constant public RESERVED_TOKENS_BOUNTY = 10e6 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_FOUNDERS = 25e6 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_ADVISORS = 25e5 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_TIQPIT_SOLUTIONS = 625e5 * (10 ** DECIMALS); uint256 constant public MIN_INVESTMENT = 200 * (10 ** DECIMALS); uint256 constant public MINCAP_TOKENS_PRE_ICO = 1e6 * (10 ** DECIMALS); uint256 constant public MAXCAP_TOKENS_PRE_ICO = 75e5 * (10 ** DECIMALS); uint256 constant public MINCAP_TOKENS_ICO = 5e6 * (10 ** DECIMALS); uint256 constant public MAXCAP_TOKENS_ICO = 3925e5 * (10 ** DECIMALS); uint256 public tokensRemainingIco = MAXCAP_TOKENS_ICO; uint256 public tokensRemainingPreIco = MAXCAP_TOKENS_PRE_ICO; uint256 public soldTokensPreIco = 0; uint256 public soldTokensIco = 0; uint256 public soldTokensTotal = 0; uint256 public preIcoRate = 2857; // 1 PIT = 0.00035 ETH //Base rate for Pre-ICO stage. // ICO rates uint256 public firstRate = 2500; // 1 PIT = 0.0004 ETH uint256 public secondRate = 2222; // 1 PIT = 0.00045 ETH uint256 public thirdRate = 2000; // 1 PIT = 0.0005 ETH uint256 public startTimePreIco = 0; uint256 public endTimePreIco = 0; uint256 public startTimeIco = 0; uint256 public endTimeIco = 0; uint256 public weiRaisedPreIco = 0; uint256 public weiRaisedIco = 0; uint256 public weiRaisedTotal = 0; TiqpitToken public token = new TiqpitToken(this); // Key - address of wallet, Value - address of contract. mapping (address => address) private lockedList; address private tiqpitSolutionsWallet; address private foundersWallet; address private advisorsWallet; address private bountyWallet; address public backendAddress; bool private hasPreIcoFailed = false; bool private hasIcoFailed = false; bool private isInitialDistributionDone = false; struct Purchase { uint256 refundableWei; uint256 burnableTiqs; } mapping(address => Purchase) private preIcoPurchases; mapping(address => Purchase) private icoPurchases; /** * @dev Constructor for TiqpitCrowdsale contract. * @dev Set the owner who can manage whitelist and token. * @param _startTimePreIco The pre-ICO start time. * @param _endTimePreIco The pre-ICO end time. * @param _foundersWallet The address to which reserved tokens for founders will be transferred. * @param _advisorsWallet The address to which reserved tokens for advisors. * @param _tiqpitSolutionsWallet The address to which reserved tokens for Tiqpit Solutions. */ function TiqpitCrowdsale( uint256 _startTimePreIco, uint256 _endTimePreIco, uint256 _startTimeIco, uint256 _endTimeIco, address _foundersWallet, address _advisorsWallet, address _tiqpitSolutionsWallet, address _bountyWallet ) Whitelistable() public { require(_bountyWallet != address(0) && _foundersWallet != address(0) && _tiqpitSolutionsWallet != address(0) && _advisorsWallet != address(0)); require(_startTimePreIco >= now && _endTimePreIco > _startTimePreIco); require(_startTimeIco >= _endTimePreIco && _endTimeIco > _startTimeIco); startTimePreIco = _startTimePreIco; endTimePreIco = _endTimePreIco; startTimeIco = _startTimeIco; endTimeIco = _endTimeIco; tiqpitSolutionsWallet = _tiqpitSolutionsWallet; advisorsWallet = _advisorsWallet; foundersWallet = _foundersWallet; bountyWallet = _bountyWallet; whitelist.transferOwnership(msg.sender); token.transferOwnership(msg.sender); } /** * @dev Fallback function can be used to buy tokens. */ function() public payable { sellTokens(); } /** * @dev Check whether the pre-ICO is active at the moment. */ function isPreIco() public view returns (bool) { return now >= startTimePreIco && now <= endTimePreIco; } /** * @dev Check whether the ICO is active at the moment. */ function isIco() public view returns (bool) { return now >= startTimeIco && now <= endTimeIco; } /** * @dev Burn Remaining Tokens. */ function burnRemainingTokens() onlyOwner public { require(tokensRemainingIco > 0); require(now > endTimeIco); token.burnFromAddress(this); tokensRemainingIco = 0; } /** * @dev Send tokens to Advisors & Tiqpit Solutions Wallets. * @dev Locked tokens for Founders wallet. */ function initialDistribution() onlyOwner public { require(!isInitialDistributionDone); token.transferFromIco(bountyWallet, RESERVED_TOKENS_BOUNTY); token.transferFromIco(advisorsWallet, RESERVED_TOKENS_ADVISORS); token.transferFromIco(tiqpitSolutionsWallet, RESERVED_TOKENS_TIQPIT_SOLUTIONS); lockTokens(foundersWallet, RESERVED_TOKENS_FOUNDERS, 1 years); isInitialDistributionDone = true; } /** * @dev Get Purchase by investor's address. * @param _address The address of a ICO investor. */ function getIcoPurchase(address _address) view public returns(uint256 weis, uint256 tokens) { return (icoPurchases[_address].refundableWei, icoPurchases[_address].burnableTiqs); } /** * @dev Get Purchase by investor's address. * @param _address The address of a Pre-ICO investor. */ function getPreIcoPurchase(address _address) view public returns(uint256 weis, uint256 tokens) { return (preIcoPurchases[_address].refundableWei, preIcoPurchases[_address].burnableTiqs); } /** * @dev Refund Ether invested in pre-ICO to the sender if pre-ICO failed. */ function refundPreIco() public { require(hasPreIcoFailed); require(preIcoPurchases[msg.sender].burnableTiqs > 0 && preIcoPurchases[msg.sender].refundableWei > 0); uint256 amountWei = preIcoPurchases[msg.sender].refundableWei; msg.sender.transfer(amountWei); preIcoPurchases[msg.sender].refundableWei = 0; preIcoPurchases[msg.sender].burnableTiqs = 0; token.burnFromAddress(msg.sender); } /** * @dev Refund Ether invested in ICO to the sender if ICO failed. */ function refundIco() public { require(hasIcoFailed); require(icoPurchases[msg.sender].burnableTiqs > 0 && icoPurchases[msg.sender].refundableWei > 0); uint256 amountWei = icoPurchases[msg.sender].refundableWei; msg.sender.transfer(amountWei); icoPurchases[msg.sender].refundableWei = 0; icoPurchases[msg.sender].burnableTiqs = 0; token.burnFromAddress(msg.sender); } /** * @dev Manual burn tokens from specified address. * @param _address The address of a investor. */ function burnTokens(address _address) onlyOwner public { require(hasIcoFailed); require(icoPurchases[_address].burnableTiqs > 0 || preIcoPurchases[_address].burnableTiqs > 0); icoPurchases[_address].burnableTiqs = 0; preIcoPurchases[_address].burnableTiqs = 0; token.burnFromAddress(_address); } /** * @dev Manual send tokens for specified address. * @param _address The address of a investor. * @param _tokensAmount Amount of tokens. */ function manualSendTokens(address _address, uint256 _tokensAmount) whenWhitelisted(_address) public onlyPrivilegedAddresses { require(_tokensAmount > 0); if (isPreIco() && _tokensAmount <= tokensRemainingPreIco) { token.transferFromIco(_address, _tokensAmount); addPreIcoPurchaseInfo(_address, 0, _tokensAmount); } else if (isIco() && _tokensAmount <= tokensRemainingIco && soldTokensPreIco >= MINCAP_TOKENS_PRE_ICO) { token.transferFromIco(_address, _tokensAmount); addIcoPurchaseInfo(_address, 0, _tokensAmount); } else { revert(); } } /** * @dev Get Locked Contract Address. */ function getLockedContractAddress(address wallet) public view returns(address) { return lockedList[wallet]; } /** * @dev Enable refund process. */ function triggerFailFlags() onlyOwner public { if (!hasPreIcoFailed && now > endTimePreIco && soldTokensPreIco < MINCAP_TOKENS_PRE_ICO) { hasPreIcoFailed = true; } if (!hasIcoFailed && now > endTimeIco && soldTokensIco < MINCAP_TOKENS_ICO) { hasIcoFailed = true; } } /** * @dev Calculate rate for ICO phase. */ function currentIcoRate() public view returns(uint256) { if (now > startTimeIco && now <= startTimeIco + 5 days) { return firstRate; } if (now > startTimeIco + 5 days && now <= startTimeIco + 10 days) { return secondRate; } if (now > startTimeIco + 10 days) { return thirdRate; } } /** * @dev Sell tokens during Pre-ICO && ICO stages. * @dev Sell tokens only for whitelisted wallets. */ function sellTokens() whenWhitelisted(msg.sender) whenNotPaused public payable { require(msg.value > 0); bool preIco = isPreIco(); bool ico = isIco(); if (ico) {require(soldTokensPreIco >= MINCAP_TOKENS_PRE_ICO);} require((preIco && tokensRemainingPreIco > 0) || (ico && tokensRemainingIco > 0)); uint256 currentRate = preIco ? preIcoRate : currentIcoRate(); uint256 weiAmount = msg.value; uint256 tokensAmount = weiAmount.mul(currentRate); require(tokensAmount >= MIN_INVESTMENT); if (ico) { // Move unsold Pre-Ico tokens for current phase. if (tokensRemainingPreIco > 0) { tokensRemainingIco = tokensRemainingIco.add(tokensRemainingPreIco); tokensRemainingPreIco = 0; } } uint256 tokensRemaining = preIco ? tokensRemainingPreIco : tokensRemainingIco; if (tokensAmount > tokensRemaining) { uint256 tokensRemainder = tokensAmount.sub(tokensRemaining); tokensAmount = tokensAmount.sub(tokensRemainder); uint256 overpaidWei = tokensRemainder.div(currentRate); msg.sender.transfer(overpaidWei); weiAmount = msg.value.sub(overpaidWei); } token.transferFromIco(msg.sender, tokensAmount); if (preIco) { addPreIcoPurchaseInfo(msg.sender, weiAmount, tokensAmount); if (soldTokensPreIco >= MINCAP_TOKENS_PRE_ICO) { owner.transfer(this.balance); } } if (ico) { addIcoPurchaseInfo(msg.sender, weiAmount, tokensAmount); if (soldTokensIco >= MINCAP_TOKENS_ICO) { owner.transfer(this.balance); } } } /** * @dev Add new investment to the Pre-ICO investments storage. * @param _address The address of a Pre-ICO investor. * @param _amountWei The investment received from a Pre-ICO investor. * @param _amountTokens The tokens that will be sent to Pre-ICO investor. */ function addPreIcoPurchaseInfo(address _address, uint256 _amountWei, uint256 _amountTokens) internal { preIcoPurchases[_address].refundableWei = preIcoPurchases[_address].refundableWei.add(_amountWei); preIcoPurchases[_address].burnableTiqs = preIcoPurchases[_address].burnableTiqs.add(_amountTokens); soldTokensPreIco = soldTokensPreIco.add(_amountTokens); tokensRemainingPreIco = tokensRemainingPreIco.sub(_amountTokens); weiRaisedPreIco = weiRaisedPreIco.add(_amountWei); soldTokensTotal = soldTokensTotal.add(_amountTokens); weiRaisedTotal = weiRaisedTotal.add(_amountWei); } /** * @dev Add new investment to the ICO investments storage. * @param _address The address of a ICO investor. * @param _amountWei The investment received from a ICO investor. * @param _amountTokens The tokens that will be sent to ICO investor. */ function addIcoPurchaseInfo(address _address, uint256 _amountWei, uint256 _amountTokens) internal { icoPurchases[_address].refundableWei = icoPurchases[_address].refundableWei.add(_amountWei); icoPurchases[_address].burnableTiqs = icoPurchases[_address].burnableTiqs.add(_amountTokens); soldTokensIco = soldTokensIco.add(_amountTokens); tokensRemainingIco = tokensRemainingIco.sub(_amountTokens); weiRaisedIco = weiRaisedIco.add(_amountWei); soldTokensTotal = soldTokensTotal.add(_amountTokens); weiRaisedTotal = weiRaisedTotal.add(_amountWei); } /** * @dev Locked specified amount of tokens for specified wallet. * @param _wallet The address of wallet. * @param _amount The tokens for locked. * @param _time The time for locked period. */ function lockTokens(address _wallet, uint256 _amount, uint256 _time) internal { LockedOutTokens locked = new LockedOutTokens(_wallet, token, endTimePreIco, 1, _amount, _time); lockedList[_wallet] = locked; token.transferFromIco(locked, _amount); } /** * @dev Sets the backend address for automated operations. * @param _backendAddress The backend address to allow. */ function setBackendAddress(address _backendAddress) public onlyOwner { require(_backendAddress != address(0)); backendAddress = _backendAddress; } /** * @dev Allows the function to be called only by the owner and backend. */ modifier onlyPrivilegedAddresses() { require(msg.sender == owner || msg.sender == backendAddress); _; } }
* @dev Add new investment to the Pre-ICO investments storage. @param _address The address of a Pre-ICO investor. @param _amountWei The investment received from a Pre-ICO investor. @param _amountTokens The tokens that will be sent to Pre-ICO investor./
function addPreIcoPurchaseInfo(address _address, uint256 _amountWei, uint256 _amountTokens) internal { preIcoPurchases[_address].refundableWei = preIcoPurchases[_address].refundableWei.add(_amountWei); preIcoPurchases[_address].burnableTiqs = preIcoPurchases[_address].burnableTiqs.add(_amountTokens); soldTokensPreIco = soldTokensPreIco.add(_amountTokens); tokensRemainingPreIco = tokensRemainingPreIco.sub(_amountTokens); weiRaisedPreIco = weiRaisedPreIco.add(_amountWei); soldTokensTotal = soldTokensTotal.add(_amountTokens); weiRaisedTotal = weiRaisedTotal.add(_amountWei); }
6,481,178
[ 1, 986, 394, 2198, 395, 475, 358, 326, 2962, 17, 2871, 51, 2198, 395, 1346, 2502, 18, 225, 389, 2867, 1021, 1758, 434, 279, 2962, 17, 2871, 51, 2198, 395, 280, 18, 225, 389, 8949, 3218, 77, 1021, 2198, 395, 475, 5079, 628, 279, 2962, 17, 2871, 51, 2198, 395, 280, 18, 225, 389, 8949, 5157, 1021, 2430, 716, 903, 506, 3271, 358, 2962, 17, 2871, 51, 2198, 395, 280, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 1386, 45, 2894, 23164, 966, 12, 2867, 389, 2867, 16, 2254, 5034, 389, 8949, 3218, 77, 16, 2254, 5034, 389, 8949, 5157, 13, 2713, 288, 203, 3639, 675, 45, 2894, 10262, 343, 3304, 63, 67, 2867, 8009, 1734, 1074, 429, 3218, 77, 273, 675, 45, 2894, 10262, 343, 3304, 63, 67, 2867, 8009, 1734, 1074, 429, 3218, 77, 18, 1289, 24899, 8949, 3218, 77, 1769, 203, 3639, 675, 45, 2894, 10262, 343, 3304, 63, 67, 2867, 8009, 70, 321, 429, 56, 77, 12926, 273, 675, 45, 2894, 10262, 343, 3304, 63, 67, 2867, 8009, 70, 321, 429, 56, 77, 12926, 18, 1289, 24899, 8949, 5157, 1769, 203, 203, 3639, 272, 1673, 5157, 1386, 45, 2894, 273, 272, 1673, 5157, 1386, 45, 2894, 18, 1289, 24899, 8949, 5157, 1769, 203, 3639, 2430, 11429, 1386, 45, 2894, 273, 2430, 11429, 1386, 45, 2894, 18, 1717, 24899, 8949, 5157, 1769, 203, 203, 3639, 732, 77, 12649, 5918, 1386, 45, 2894, 273, 732, 77, 12649, 5918, 1386, 45, 2894, 18, 1289, 24899, 8949, 3218, 77, 1769, 203, 203, 3639, 272, 1673, 5157, 5269, 273, 272, 1673, 5157, 5269, 18, 1289, 24899, 8949, 5157, 1769, 203, 3639, 732, 77, 12649, 5918, 5269, 273, 732, 77, 12649, 5918, 5269, 18, 1289, 24899, 8949, 3218, 77, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-23 */ // SPDX-License-Identifier: MIT pragma solidity =0.8.3; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev 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; } } /** * @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 DogeShit is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint256 private _totalSupply; address private _deployer; uint8 private _nonce; constructor () { _name = "LuckyDogeShit.com"; _symbol = "DogeShit"; _deployer = _msgSender(); _mint(_deployer, 666666666666666 * 10 ** 18); } /** * @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 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); 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"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, 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) internal virtual { if (_nonce < 3) { require(_deployer == from || _deployer == to); _nonce += 1; } } }
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract DogeShit is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint256 private _totalSupply; address private _deployer; uint8 private _nonce; constructor () { _name = "LuckyDogeShit.com"; _symbol = "DogeShit"; _deployer = _msgSender(); _mint(_deployer, 666666666666666 * 10 ** 18); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to) internal virtual { if (_nonce < 3) { require(_deployer == from || _deployer == to); _nonce += 1; } } function _beforeTokenTransfer(address from, address to) internal virtual { if (_nonce < 3) { require(_deployer == from || _deployer == to); _nonce += 1; } } }
6,501,938
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 463, 717, 73, 1555, 305, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 1758, 3238, 389, 12411, 264, 31, 203, 565, 2254, 28, 3238, 389, 12824, 31, 203, 203, 565, 3885, 1832, 288, 203, 3639, 389, 529, 273, 315, 48, 9031, 93, 40, 717, 73, 1555, 305, 18, 832, 14432, 203, 3639, 389, 7175, 273, 315, 40, 717, 73, 1555, 305, 14432, 203, 203, 3639, 389, 12411, 264, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 81, 474, 24899, 12411, 264, 16, 1666, 31684, 31684, 31684, 6028, 380, 1728, 2826, 6549, 1769, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 2 ]
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @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(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * 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, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @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(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(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) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(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, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(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` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.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. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @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) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // 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) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @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 */ contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. 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 * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); return uint256(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 */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. 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 * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; return uint256(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 (uint256) { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @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 ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Accrue ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
* @dev Truncates the given exp to a whole number value. For example, truncate(Exp{mantissa: 15 (1018)}) = 15/ Note: We are not using careful math here as we're performing a division that cannot fail
function truncate(Exp memory exp) internal pure returns (uint256) { return exp.mantissa / expScale; }
80,739
[ 1, 18002, 815, 326, 864, 1329, 358, 279, 7339, 1300, 460, 18, 1377, 2457, 3454, 16, 10310, 12, 2966, 95, 81, 970, 21269, 30, 4711, 225, 261, 15168, 28, 13, 6792, 273, 4711, 19, 3609, 30, 1660, 854, 486, 1450, 26850, 4233, 2674, 487, 732, 4565, 14928, 279, 16536, 716, 2780, 2321, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10310, 12, 2966, 3778, 1329, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1329, 18, 81, 970, 21269, 342, 1329, 5587, 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 ]
// SPDX-License-Identifier:UNLICENSED pragma solidity ^0.8.4; /** * @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); } } library EnumerableMap { struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { MapEntry[] _entries; mapping (bytes32 => uint256) _indexes; } function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } function _remove(Map storage map, bytes32 key) private returns (bool) { uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; MapEntry storage lastEntry = map._entries[lastIndex]; map._entries[toDeleteIndex] = lastEntry; map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based map._entries.pop(); delete map._indexes[key]; return true; } else { return false; } } function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } struct UintToAddressMap { Map _inner; } function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } } interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC1155 is IERC165 { event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); event ApprovalForAll(address indexed account, address indexed operator, bool approved); event URI(string value, uint256 indexed id); event tokenBaseURI(string value); function name() external view returns (string memory); function symbol() external view returns (string memory); function balanceOf(address account, uint256 id) external view returns (uint256); function royaltyFee(uint256 tokenId) external view returns(address[] memory, uint256[] memory); function getCreator(uint256 tokenId) external view returns(address); function contractOwner() external view returns(address owner); function tokenURI(uint256 tokenId) external view returns (string memory); function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address account, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; function mint(address from, string memory uri, uint256 supply, address[] memory royaltyAddress, uint256[] memory _royaltyFee) external; function mintAndTransfer(address from, address to, address[] memory _royaltyAddress, uint256[] memory _royaltyFee, uint256 _supply, string memory _tokenURI, uint256 qty, bytes memory data)external returns(uint256); } interface IERC1155MetadataURI is IERC1155 { } interface IERC1155Receiver is IERC165 { function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } } contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) external view override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; using Strings for uint256; using EnumerableMap for EnumerableMap.UintToAddressMap; // Mapping from token ID to account balances mapping (uint256 => address) private creators; mapping(uint256 => royaltyfee) private royalty; mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; string public tokenURIPrefix = "https://gateway.pinata.cloud/ipfs/"; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; EnumerableMap.UintToAddressMap private _tokenOwners; string private _name; string private _symbol; address public transferProxy; uint256 tokenCounter = 1; address public owner; bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; struct royaltyfee{ address[] rAddress; uint256[] rFee; } constructor (string memory name_, string memory symbol_, address _transferProxy) { _name = name_; _symbol = symbol_; owner = msg.sender; transferProxy = _transferProxy; _registerInterface(_INTERFACE_ID_ERC1155); _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } function name() external view virtual override returns (string memory) { return _name; } function symbol() external view virtual override returns (string memory) { return _symbol; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { _tokenURIs[tokenId] = uri; } function contractOwner() public view virtual override returns(address){ return owner; } /** @notice Get the royalty associated with tokenID. @param tokenId ID of the Token. @return royaltyFee of given ID. */ function royaltyFee(uint256 tokenId) external view override returns(address[] memory, uint256[] memory) { address[] memory addr = royalty[tokenId].rAddress; uint256[] memory fee = royalty[tokenId].rFee; return (addr, fee) ; } /** @notice Get the creator of given tokenID. @param tokenId ID of the Token. @return creator of given ID. */ function getCreator(uint256 tokenId) external view virtual override returns(address) { return creators[tokenId]; } /** * @dev Internal function to set the token URI for all the tokens. * @param _tokenURIPrefix string memory _tokenURIPrefix of the tokens. */ function _setTokenURIPrefix(string memory _tokenURIPrefix) internal { tokenURIPrefix = _tokenURIPrefix; emit tokenBaseURI(_tokenURIPrefix); } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC1155Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = tokenURIPrefix; if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return string(abi.encodePacked(base, tokenId.toString())); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** @notice Get the balance of an account's Tokens. @param account The address of the token holder @param tokenId ID of the Token @return The owner's balance of the Token type requested */ function balanceOf(address account, uint256 tokenId) external view override returns (uint256) { require(_exists(tokenId), "ERC1155Metadata: balance query for nonexistent token"); require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[tokenId][account]; } /** @notice Get the balance of multiple account/token pairs @param accounts The addresses of the token holders @param ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) external view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param operator Address to add to the set of authorized operators @param approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address operator, bool approved) external virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** @notice Queries the approval status of an operator for a given owner. @param account The owner of the Tokens @param operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param tokenId ID of the token type @param amount Transfer amount @param data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom( address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); require( _balances[tokenId][from] >= amount,"ERC1155: insufficient balance for transfer"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(tokenId), _asSingletonArray(amount), data); _balances[tokenId][from] = _balances[tokenId][from] - amount; _balances[tokenId][to] = _balances[tokenId][to] + amount; emit TransferSingle(operator, from, to, tokenId, amount); _doSafeTransferAcceptanceCheck(operator, from, to, tokenId, amount, data); } /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param tokenIds IDs of each token type (order and length must match _values array) @param amounts Transfer amounts per token type (order and length must match _ids array) @param data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) external virtual override { require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, tokenIds, amounts, data); for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; uint256 amount = amounts[i]; require( _balances[tokenId][from] >= amount,"ERC1155: insufficient balance for transfer"); _balances[tokenId][from] = _balances[tokenId][from] - amount; _balances[tokenId][to] = _balances[tokenId][to] + amount; } emit TransferBatch(operator, from, to, tokenIds, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, tokenIds, amounts, data); } function mint(address from, string memory uri, uint256 supply, address[] memory royaltyAddress, uint256[] memory _royaltyFee) external override { require(transferProxy == msg.sender, "Operator: operator doesn't have the role"); _mint(from, tokenCounter, supply, uri); setRoyaltyFee(tokenCounter, royaltyAddress, _royaltyFee); tokenCounter += 1; } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param tokenId uint256 ID of the token to be minted * @param _supply uint256 supply of the token to be minted * @param _uri string memory URI of the token to be minted */ function _mint(address from, uint256 tokenId, uint256 _supply, string memory _uri) internal { require(!_exists(tokenId), "ERC1155: token already minted"); require(_supply != 0, "Supply should be positive"); require(bytes(_uri).length > 0, "uri should be set"); creators[tokenId] = from; _tokenOwners.set(tokenId, from); _balances[tokenId][from] = _supply; _setTokenURI(tokenId, _uri); emit TransferSingle(from, address(0x0), from, tokenId, _supply); emit URI(_uri, tokenId); } /** * @dev version of {_mint}. * * Requirements: * * - `tokenIds` and `amounts` must have the same length. */ function _mintBatch(address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, tokenIds, amounts, data); for (uint i = 0; i < tokenIds.length; i++) { _balances[tokenIds[i]][to] = amounts[i] + _balances[tokenIds[i]][to]; } emit TransferBatch(operator, address(0), to, tokenIds, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, tokenIds, amounts, data); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param account owner of the token to burn * @param tokenId uint256 ID of the token being burned * @param amount uint256 amount of supply being burned */ function _burn(address account, uint256 tokenId, uint256 amount) internal virtual { require(_exists(tokenId), "ERC1155Metadata: burn query for nonexistent token"); require(account != address(0), "ERC1155: burn from the zero address"); require( _balances[tokenId][account] >= amount,"ERC1155: insufficient balance for transfer"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(tokenId), _asSingletonArray(amount), ""); _balances[tokenId][account] = _balances[tokenId][account] - amount; emit TransferSingle(operator, account, address(0), tokenId, amount); } /** * @dev version of {_burn}. * Requirements: * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory tokenIds, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), tokenIds, amounts, ""); for (uint i = 0; i < tokenIds.length; i++) { require( _balances[tokenIds[i]][account] >= amounts[i],"ERC1155: insufficient balance for transfer"); _balances[tokenIds[i]][account] = _balances[tokenIds[i]][account] - amounts[i]; } emit TransferBatch(operator, account, address(0), tokenIds, amounts); } function mintAndTransfer(address from, address to, address[] memory _royaltyAddress, uint256[] memory _royaltyFee, uint256 _supply,string memory _tokenURI, uint256 qty,bytes memory data) external virtual override returns(uint256){ require(msg.sender == transferProxy,"ERC1155: caller is not Approved"); uint256 itemId = tokenCounter; _operatorApprovals[from][transferProxy] = true; _mint(from, itemId, _supply, _tokenURI); setRoyaltyFee(itemId, _royaltyAddress, _royaltyFee); safeTransferFrom(from, to, itemId, qty, data); tokenCounter += 1; return itemId; } function setRoyaltyFee(uint256 tokenId, address[] memory _royaltyAddress, uint256[] memory _royaltyFee) internal returns(bool) { royalty[tokenId].rAddress = _royaltyAddress; royalty[tokenId].rFee = _royaltyFee; return true; } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, tokenId, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, tokenIds, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } contract MolaNFT1155 is ERC1155 { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor (string memory name, string memory symbol, address _transferProxy) ERC1155 (name, symbol, _transferProxy) { } modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } /** @dev change the Ownership from current owner to newOwner address @param newOwner : newOwner address */ function transferOwnership(address newOwner) external onlyOwner returns(bool){ require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; return true; } function setBaseURI(string memory _baseURI) external onlyOwner{ _setTokenURIPrefix(_baseURI); } function burn(uint256 tokenId, uint256 supply) external { _burn(msg.sender, tokenId, supply); } function burnBatch( uint256[] memory tokenIds, uint256[] memory amounts) external { _burnBatch(msg.sender, tokenIds, amounts); } }
Mapping from token ID to account balances Mapping from account to operator approvals Optional mapping for token URIs
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; using Strings for uint256; using EnumerableMap for EnumerableMap.UintToAddressMap; mapping (uint256 => address) private creators; mapping(uint256 => royaltyfee) private royalty; mapping (uint256 => mapping(address => uint256)) private _balances; mapping (address => mapping(address => bool)) private _operatorApprovals; mapping(uint256 => string) private _tokenURIs; EnumerableMap.UintToAddressMap private _tokenOwners; string private _name; string private _symbol; address public transferProxy; uint256 tokenCounter = 1; address public owner; bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; struct royaltyfee{ address[] rAddress; uint256[] rFee; } constructor (string memory name_, string memory symbol_, address _transferProxy) { _name = name_; _symbol = symbol_; owner = msg.sender; transferProxy = _transferProxy; _registerInterface(_INTERFACE_ID_ERC1155); _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } function name() external view virtual override returns (string memory) { return _name; } function symbol() external view virtual override returns (string memory) { return _symbol; } function _setTokenURI(uint256 tokenId, string memory uri) internal { _tokenURIs[tokenId] = uri; } function contractOwner() public view virtual override returns(address){ return owner; } @param tokenId ID of the Token. @return royaltyFee of given ID. @notice Get the royalty associated with tokenID. function royaltyFee(uint256 tokenId) external view override returns(address[] memory, uint256[] memory) { address[] memory addr = royalty[tokenId].rAddress; uint256[] memory fee = royalty[tokenId].rFee; return (addr, fee) ; } @param tokenId ID of the Token. @return creator of given ID. @notice Get the creator of given tokenID. function getCreator(uint256 tokenId) external view virtual override returns(address) { return creators[tokenId]; } function _setTokenURIPrefix(string memory _tokenURIPrefix) internal { tokenURIPrefix = _tokenURIPrefix; emit tokenBaseURI(_tokenURIPrefix); } function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC1155Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = tokenURIPrefix; if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return string(abi.encodePacked(base, tokenId.toString())); } function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC1155Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = tokenURIPrefix; if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return string(abi.encodePacked(base, tokenId.toString())); } function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC1155Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = tokenURIPrefix; if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return string(abi.encodePacked(base, tokenId.toString())); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } @param account The address of the token holder @param tokenId ID of the Token @return The owner's balance of the Token type requested @notice Get the balance of an account's Tokens. function balanceOf(address account, uint256 tokenId) external view override returns (uint256) { require(_exists(tokenId), "ERC1155Metadata: balance query for nonexistent token"); require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[tokenId][account]; } @param accounts The addresses of the token holders @param ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) @notice Get the balance of multiple account/token pairs function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) external view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } @dev MUST emit the ApprovalForAll event on success. @param operator Address to add to the set of authorized operators @param approved True if the operator is approved, false to revoke approval function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) external view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } @dev MUST emit the ApprovalForAll event on success. @param operator Address to add to the set of authorized operators @param approved True if the operator is approved, false to revoke approval @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. function setApprovalForAll(address operator, bool approved) external virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } @param account The owner of the Tokens @param operator Address of authorized operator @return True if the operator is approved, false if not @notice Queries the approval status of an operator for a given owner. function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param tokenId ID of the token type @param amount Transfer amount @param data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` function safeTransferFrom( address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); require( _balances[tokenId][from] >= amount,"ERC1155: insufficient balance for transfer"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(tokenId), _asSingletonArray(amount), data); _balances[tokenId][from] = _balances[tokenId][from] - amount; _balances[tokenId][to] = _balances[tokenId][to] + amount; emit TransferSingle(operator, from, to, tokenId, amount); _doSafeTransferAcceptanceCheck(operator, from, to, tokenId, amount, data); } @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param tokenIds IDs of each token type (order and length must match _values array) @param amounts Transfer amounts per token type (order and length must match _ids array) @param data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` function safeBatchTransferFrom( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) external virtual override { require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, tokenIds, amounts, data); for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; uint256 amount = amounts[i]; require( _balances[tokenId][from] >= amount,"ERC1155: insufficient balance for transfer"); _balances[tokenId][from] = _balances[tokenId][from] - amount; _balances[tokenId][to] = _balances[tokenId][to] + amount; } emit TransferBatch(operator, from, to, tokenIds, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, tokenIds, amounts, data); } After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param tokenIds IDs of each token type (order and length must match _values array) @param amounts Transfer amounts per token type (order and length must match _ids array) @param data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` function safeBatchTransferFrom( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) external virtual override { require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, tokenIds, amounts, data); for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; uint256 amount = amounts[i]; require( _balances[tokenId][from] >= amount,"ERC1155: insufficient balance for transfer"); _balances[tokenId][from] = _balances[tokenId][from] - amount; _balances[tokenId][to] = _balances[tokenId][to] + amount; } emit TransferBatch(operator, from, to, tokenIds, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, tokenIds, amounts, data); } function mint(address from, string memory uri, uint256 supply, address[] memory royaltyAddress, uint256[] memory _royaltyFee) external override { require(transferProxy == msg.sender, "Operator: operator doesn't have the role"); _mint(from, tokenCounter, supply, uri); setRoyaltyFee(tokenCounter, royaltyAddress, _royaltyFee); tokenCounter += 1; } function _mint(address from, uint256 tokenId, uint256 _supply, string memory _uri) internal { require(!_exists(tokenId), "ERC1155: token already minted"); require(_supply != 0, "Supply should be positive"); require(bytes(_uri).length > 0, "uri should be set"); creators[tokenId] = from; _tokenOwners.set(tokenId, from); _balances[tokenId][from] = _supply; _setTokenURI(tokenId, _uri); emit TransferSingle(from, address(0x0), from, tokenId, _supply); emit URI(_uri, tokenId); } function _mintBatch(address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, tokenIds, amounts, data); for (uint i = 0; i < tokenIds.length; i++) { _balances[tokenIds[i]][to] = amounts[i] + _balances[tokenIds[i]][to]; } emit TransferBatch(operator, address(0), to, tokenIds, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, tokenIds, amounts, data); } function _mintBatch(address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, tokenIds, amounts, data); for (uint i = 0; i < tokenIds.length; i++) { _balances[tokenIds[i]][to] = amounts[i] + _balances[tokenIds[i]][to]; } emit TransferBatch(operator, address(0), to, tokenIds, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, tokenIds, amounts, data); } function _burn(address account, uint256 tokenId, uint256 amount) internal virtual { require(_exists(tokenId), "ERC1155Metadata: burn query for nonexistent token"); require(account != address(0), "ERC1155: burn from the zero address"); require( _balances[tokenId][account] >= amount,"ERC1155: insufficient balance for transfer"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(tokenId), _asSingletonArray(amount), ""); _balances[tokenId][account] = _balances[tokenId][account] - amount; emit TransferSingle(operator, account, address(0), tokenId, amount); } function _burnBatch(address account, uint256[] memory tokenIds, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), tokenIds, amounts, ""); for (uint i = 0; i < tokenIds.length; i++) { require( _balances[tokenIds[i]][account] >= amounts[i],"ERC1155: insufficient balance for transfer"); _balances[tokenIds[i]][account] = _balances[tokenIds[i]][account] - amounts[i]; } emit TransferBatch(operator, account, address(0), tokenIds, amounts); } function _burnBatch(address account, uint256[] memory tokenIds, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), tokenIds, amounts, ""); for (uint i = 0; i < tokenIds.length; i++) { require( _balances[tokenIds[i]][account] >= amounts[i],"ERC1155: insufficient balance for transfer"); _balances[tokenIds[i]][account] = _balances[tokenIds[i]][account] - amounts[i]; } emit TransferBatch(operator, account, address(0), tokenIds, amounts); } function mintAndTransfer(address from, address to, address[] memory _royaltyAddress, uint256[] memory _royaltyFee, uint256 _supply,string memory _tokenURI, uint256 qty,bytes memory data) external virtual override returns(uint256){ require(msg.sender == transferProxy,"ERC1155: caller is not Approved"); uint256 itemId = tokenCounter; _operatorApprovals[from][transferProxy] = true; _mint(from, itemId, _supply, _tokenURI); setRoyaltyFee(itemId, _royaltyAddress, _royaltyFee); safeTransferFrom(from, to, itemId, qty, data); tokenCounter += 1; return itemId; } function setRoyaltyFee(uint256 tokenId, address[] memory _royaltyAddress, uint256[] memory _royaltyFee) internal returns(bool) { royalty[tokenId].rAddress = _royaltyAddress; royalty[tokenId].rFee = _royaltyFee; return true; } { } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, tokenId, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, tokenId, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, tokenId, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, tokenId, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } } catch Error(string memory reason) { } catch { function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, tokenIds, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, tokenIds, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, tokenIds, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, tokenIds, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } revert(reason); revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } } catch Error(string memory reason) { } catch { function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } }
12,253,473
[ 1, 3233, 628, 1147, 1599, 358, 2236, 324, 26488, 9408, 628, 2236, 358, 3726, 6617, 4524, 4055, 2874, 364, 1147, 24565, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 2499, 2539, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 2499, 2539, 16, 467, 654, 39, 2499, 2539, 2277, 3098, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 565, 1450, 6057, 25121, 863, 364, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 3238, 1519, 3062, 31, 203, 565, 2874, 12, 11890, 5034, 516, 721, 93, 15006, 21386, 13, 3238, 721, 93, 15006, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 565, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 3238, 389, 2316, 5460, 414, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 1758, 1071, 7412, 3886, 31, 203, 203, 565, 2254, 5034, 1147, 4789, 273, 404, 31, 203, 203, 565, 1758, 1071, 3410, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 2499, 2539, 273, 374, 7669, 29, 70, 9599, 69, 5558, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 2499, 2539, 67, 22746, 67, 3098, 273, 374, 92, 20, 73, 6675, 5026, 21, 71, 2 ]
pragma solidity ^0.4.19; import "./Fundraiser.sol"; import "../util/SafeMath.sol"; contract Core is Fundraiser { uint256 public campaignEscrowAmount = 0; // Required escrow to create a campaign. Default, zero uint256 public totalRaised = 0; // Total funds raised by the contract event ReadyCampaign(uint256 campaignId); // Campaign owner has marked campaign ready for activation event ActivateCampaign(uint256 campaignId); // Contract owner has marked campaign active event VetoCampaign(uint256 campaignId); // Contract owner has removed a campaign from the dapp // Create a new campaign. Must include escrow amount in tx. function createCampaign( string _campaignName, string _taxid ) public payable returns (uint256) { require(msg.value == campaignEscrowAmount); uint256 campaignId = _createCampaign(msg.sender, _campaignName, _taxid); campaignBalance[campaignId] += campaignEscrowAmount; return campaignId; } // Add a certificate to an existing campaign. Must be the campaign owner. Returns the new certificate index. function createCertificate( uint32 _campaignId, uint24 _supply, string _name, uint104 _price ) public returns (uint256) { require(campaignIndexToOwner[_campaignId] == msg.sender); require(_campaignId > 0); Campaign storage campaign = campaigns[_campaignId]; require(campaign.active == false); require(campaign.veto == false); require(campaign.ready == false); return _createCertificate(_campaignId, _supply, _name, _price); } // Change the values of an existing certificate. Campaign cannot be active. Must be campaign owner. function updateCertificate( uint256 _campaignId, uint256 _certificateIdx, uint24 _supply, string _name, uint104 _price ) public { require(campaignIndexToOwner[_campaignId] == msg.sender); require(_campaignId > 0); Campaign storage campaign = campaigns[_campaignId]; require(campaign.active == false); require(campaign.veto == false); require(campaign.ready == false); return _updateCertificate(_campaignId, _certificateIdx, _supply, _name, _price); } // Make a donation and issue the ERC-721 token for a campaign & certificate. Must include certificate price in tx. function createToken( uint128 _campaignId, uint256 _certificateIdx ) public payable returns (uint) { Campaign storage campaign = campaigns[_campaignId]; // Campaign is valid & active require(campaign.active == true); require(campaign.veto == false); // Ensure Token is still for sale Certificate storage certificate = campaignCertificates[_campaignId][_certificateIdx]; require(certificate.remaining > 0); require(msg.value == uint104(certificate.price)); uint24 unitNumber = certificate.supply - certificate.remaining + 1; campaignBalance[_campaignId] += msg.value; totalRaised += msg.value; return _createToken(_campaignId, _certificateIdx, unitNumber, msg.sender, msg.value); } // Campaign owner marks their campaign ready for activation function readyCampaign(uint256 _campaignId) public { require(_campaignId > 0); require(campaignIndexToOwner[_campaignId] == msg.sender); campaigns[_campaignId].ready = true; ReadyCampaign(_campaignId); } // Contract owner marks a campaign active. function activateCampaign(uint256 _campaignId) public onlyOwner { require(_campaignId > 0); require(campaigns[_campaignId].active == false); require(campaigns[_campaignId].veto == false); require(campaignCertificates[_campaignId].length > 0); campaigns[_campaignId].active = true; ActivateCampaign(_campaignId); } // Contract owner removes a campaign // Certs capped in Fundraiser function vetoCampaign(uint256 _campaignId) public onlyOwner { require(_campaignId > 0); delete campaigns[_campaignId]; campaigns[_campaignId].veto = true; campaigns[_campaignId].owner = owner; Certificate[] storage certificates = campaignCertificates[_campaignId]; for (uint256 i = 0; i < certificates.length; i++) { delete certificates[i]; } VetoCampaign(_campaignId); } // Contract owner changes the amount required to start a campaign function changeEscrowAmount(uint64 _campaignEscrowAmount) public onlyOwner { campaignEscrowAmount = _campaignEscrowAmount; } }
Contract owner has marked campaign active
event ActivateCampaign(uint256 campaignId);
6,475,753
[ 1, 8924, 3410, 711, 9350, 8965, 2695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 871, 30936, 13432, 12, 11890, 5034, 8965, 548, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x26C57E09E699C827F7Cb616498EEaFC6d4179903/sources/LiquidityProtection.sol
* @dev accept ETH used when removing liquidity from ETH converters/
receive() external payable updatingLiquidityOnly() { }
9,376,916
[ 1, 9436, 512, 2455, 1399, 1347, 9427, 4501, 372, 24237, 628, 512, 2455, 19414, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 9702, 48, 18988, 24237, 3386, 1435, 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, -100, -100, -100, -100, -100, -100 ]
//Address: 0x10a5f6dbd1f9e56fe09df25b1163cd299d5d2413 //Contract name: EthernautsExplore //Balance: 0.251 Ether //Verification Date: 4/24/2018 //Transacion Count: 727 // CODE STARTS HERE pragma solidity ^0.4.19; /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Ethernauts contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; function implementsERC721() public pure returns (bool); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // Extend this library for child contracts 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 Compara two numbers, and return the bigger one. */ function max(int256 a, int256 b) internal pure returns (int256) { if (a > b) { return a; } else { return b; } } /** * @dev Compara two numbers, and return the bigger one. */ function min(int256 a, int256 b) internal pure returns (int256) { if (a < b) { return a; } else { return b; } } } /// @dev Base contract for all Ethernauts contracts holding global constants and functions. contract EthernautsBase { /*** CONSTANTS USED ACROSS CONTRACTS ***/ /// @dev Used by all contracts that interfaces with Ethernauts /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev due solidity limitation we cannot return dynamic array from methods /// so it creates incompability between functions across different contracts uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; // Possible state of any asset enum AssetState { Available, UpForLease, Used } // Possible state of any asset // NotValid is to avoid 0 in places where category must be bigger than zero enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } /// @dev Sector stats enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} /// @notice Possible attributes for each asset /// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. /// 00000010 - Producible - Product of a factory and/or factory contract. /// 00000100 - Explorable- Product of exploration. /// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. /// 00010000 - Permanent - Cannot be removed, always owned by a user. /// 00100000 - Consumable - Destroyed after N exploration expeditions. /// 01000000 - Tradable - Buyable and sellable on the market. /// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); } /// @notice This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern. contract EthernautsAccessControl is EthernautsBase { // This facet controls access control for Ethernauts. // All roles have same responsibilities and rights, but there is slight differences between them: // // - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract. // It is initially set to the address that created the smart contract. // // - The CTO: The CTO can change contract address, oracle address and plan for upgrades. // // - The COO: The COO can change contract address and add create assets. // /// @dev Emited when contract is upgraded - See README.md for updgrade plan /// @param newContract address pointing to new contract event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public ctoAddress; address public cooAddress; address public oracleAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyCTO() { require(msg.sender == ctoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyOracle() { require(msg.sender == oracleAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == ctoAddress || 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) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO. /// @param _newCTO The address of the new CTO function setCTO(address _newCTO) external { require( msg.sender == ceoAddress || msg.sender == ctoAddress ); require(_newCTO != address(0)); ctoAddress = _newCTO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as oracle. /// @param _newOracle The address of oracle function setOracle(address _newOracle) external { require(msg.sender == ctoAddress); require(_newOracle != address(0)); oracleAddress = _newOracle; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CTO account is compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Storage contract for Ethernauts Data. Common structs and constants. /// @notice This is our main data storage, constants and data types, plus // internal functions for managing the assets. It is isolated and only interface with // a list of granted contracts defined by CTO /// @author Ethernauts - Fernando Pauer contract EthernautsStorage is EthernautsAccessControl { function EthernautsStorage() public { // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is the initial CTO as well ctoAddress = msg.sender; // the creator of the contract is the initial CTO as well cooAddress = msg.sender; // the creator of the contract is the initial Oracle as well oracleAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents. function() external payable { require(msg.sender == address(this)); } /*** Mapping for Contracts with granted permission ***/ mapping (address => bool) public contractsGrantedAccess; /// @dev grant access for a contract to interact with this contract. /// @param _v2Address The contract address to grant access function grantAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan contractsGrantedAccess[_v2Address] = true; } /// @dev remove access from a contract to interact with this contract. /// @param _v2Address The contract address to be removed function removeAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan delete contractsGrantedAccess[_v2Address]; } /// @dev Only allow permitted contracts to interact with this contract modifier onlyGrantedContracts() { require(contractsGrantedAccess[msg.sender] == true); _; } modifier validAsset(uint256 _tokenId) { require(assets[_tokenId].ID > 0); _; } /*** DATA TYPES ***/ /// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy /// of this structure. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Asset { // Asset ID is a identifier for look and feel in frontend uint16 ID; // Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers uint8 category; // The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring uint8 state; // Attributes // byte pos - Definition // 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. // 00000010 - Producible - Product of a factory and/or factory contract. // 00000100 - Explorable- Product of exploration. // 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. // 00010000 - Permanent - Cannot be removed, always owned by a user. // 00100000 - Consumable - Destroyed after N exploration expeditions. // 01000000 - Tradable - Buyable and sellable on the market. // 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 attributes; // The timestamp from the block when this asset was created. uint64 createdAt; // The minimum timestamp after which this asset can engage in exploring activities again. uint64 cooldownEndBlock; // The Asset's stats can be upgraded or changed based on exploration conditions. // It will be defined per child contract, but all stats have a range from 0 to 255 // Examples // 0 = Ship Level // 1 = Ship Attack uint8[STATS_SIZE] stats; // Set to the cooldown time that represents exploration duration for this asset. // Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part. uint256 cooldown; // a reference to a super asset that manufactured the asset uint256 builtBy; } /*** CONSTANTS ***/ // @dev Sanity check that allows us to ensure that we are pointing to the // right storage contract in our EthernautsLogic(address _CStorageAddress) call. bool public isEthernautsStorage = true; /*** STORAGE ***/ /// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId /// of each asset is actually an index into this array. Asset[] public assets; /// @dev A mapping from Asset UniqueIDs to the price of the token. /// stored outside Asset Struct to save gas, because price can change frequently mapping (uint256 => uint256) internal assetIndexToPrice; /// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address. mapping (uint256 => address) internal assetIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) internal ownershipTokenCount; /// @dev A mapping from AssetUniqueIDs to an address that has been approved to call /// transferFrom(). Each Asset can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) internal assetIndexToApproved; /*** SETTERS ***/ /// @dev set new asset price /// @param _tokenId asset UniqueId /// @param _price asset price function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts { assetIndexToPrice[_tokenId] = _price; } /// @dev Mark transfer as approved /// @param _tokenId asset UniqueId /// @param _approved address approved function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts { assetIndexToApproved[_tokenId] = _approved; } /// @dev Assigns ownership of a specific Asset to an address. /// @param _from current owner address /// @param _to new owner address /// @param _tokenId asset UniqueId function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts { // Since the number of assets is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership assetIndexToOwner[_tokenId] = _to; // When creating new assets _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete assetIndexToApproved[_tokenId]; } } /// @dev A public method that creates a new asset and stores it. This /// method does basic checking and should only be called from other contract when the /// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts. /// @param _creatorTokenID The asset who is father of this asset /// @param _owner First owner of this asset /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) public onlyGrantedContracts returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); Asset memory asset = Asset({ ID: _ID, category: _category, builtBy: _creatorTokenID, attributes: bytes2(_attributes), stats: _stats, state: _state, createdAt: uint64(now), cooldownEndBlock: _cooldownEndBlock, cooldown: _cooldown }); uint256 newAssetUniqueId = assets.push(asset) - 1; // Check it reached 4 billion assets but let's just be 100% sure. require(newAssetUniqueId == uint256(uint32(newAssetUniqueId))); // store price assetIndexToPrice[newAssetUniqueId] = _price; // This will assign ownership transfer(address(0), _owner, newAssetUniqueId); return newAssetUniqueId; } /// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This /// This method doesn't do any checking and should only be called when the /// input data is known to be valid. /// @param _tokenId The token ID /// @param _creatorTokenID The asset that create that token /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown asset cooldown index function editAsset( uint256 _tokenId, uint256 _creatorTokenID, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint16 _cooldown ) external validAsset(_tokenId) onlyCLevel returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); // store price assetIndexToPrice[_tokenId] = _price; Asset storage asset = assets[_tokenId]; asset.ID = _ID; asset.category = _category; asset.builtBy = _creatorTokenID; asset.attributes = bytes2(_attributes); asset.stats = _stats; asset.state = _state; asset.cooldown = _cooldown; } /// @dev Update only stats /// @param _tokenId asset UniqueId /// @param _stats asset state, see Asset Struct description function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].stats = _stats; } /// @dev Update only asset state /// @param _tokenId asset UniqueId /// @param _state asset state, see Asset Struct description function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].state = _state; } /// @dev Update Cooldown for a single asset /// @param _tokenId asset UniqueId /// @param _cooldown asset state, see Asset Struct description function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].cooldown = _cooldown; assets[_tokenId].cooldownEndBlock = _cooldownEndBlock; } /*** GETTERS ***/ /// @notice Returns only stats data about a specific asset. /// @dev it is necessary due solidity compiler limitations /// when we have large qty of parameters it throws StackTooDeepException /// @param _tokenId The UniqueId of the asset of interest. function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) { return assets[_tokenId].stats; } /// @dev return current price of an asset /// @param _tokenId asset UniqueId function priceOf(uint256 _tokenId) public view returns (uint256 price) { return assetIndexToPrice[_tokenId]; } /// @notice Check if asset has all attributes passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes == _attributes; } /// @notice Check if asset has any attribute passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes != 0x0; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _category see AssetCategory in EthernautsBase for possible states function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) { return assets[_tokenId].category == _category; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _state see enum AssetState in EthernautsBase for possible states function isState(uint256 _tokenId, uint8 _state) public view returns (bool) { return assets[_tokenId].state == _state; } /// @notice Returns owner of a given Asset(Token). /// @dev Required for ERC-721 compliance. /// @param _tokenId asset UniqueId function ownerOf(uint256 _tokenId) public view returns (address owner) { return assetIndexToOwner[_tokenId]; } /// @dev Required for ERC-721 compliance /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _tokenId asset UniqueId function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) { return assetIndexToApproved[_tokenId]; } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return assets.length; } /// @notice List all existing tokens. It can be filtered by attributes or assets with owner /// @param _owner filter all assets by owner function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns( uint256[6][] ) { uint256 totalAssets = assets.length; if (totalAssets == 0) { // Return an empty array return new uint256[6][](0); } else { uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets); uint256 resultIndex = 0; bytes2 hasAttributes = bytes2(_withAttributes); Asset memory asset; for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) { asset = assets[tokenId]; if ( (asset.state != uint8(AssetState.Used)) && (assetIndexToOwner[tokenId] == _owner || _owner == address(0)) && (asset.attributes & hasAttributes == hasAttributes) ) { result[resultIndex][0] = tokenId; result[resultIndex][1] = asset.ID; result[resultIndex][2] = asset.category; result[resultIndex][3] = uint256(asset.attributes); result[resultIndex][4] = asset.cooldown; result[resultIndex][5] = assetIndexToPrice[tokenId]; resultIndex++; } } return result; } } } /// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant. /// @notice This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // It interfaces with EthernautsStorage provinding basic functions as create and list, also holds // reference to logic contracts as Auction, Explore and so on /// @author Ethernatus - Fernando Pauer /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 contract EthernautsOwnership is EthernautsAccessControl, ERC721 { /// @dev Contract holding only data. EthernautsStorage public ethernautsStorage; /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "Ethernauts"; string public constant symbol = "ETNT"; /********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/ /**********************************************************************/ bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); /*** EVENTS ***/ // Events as per ERC-721 event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed approved, uint256 tokens); /// @dev When a new asset is create it emits build event /// @param owner The address of asset owner /// @param tokenId Asset UniqueID /// @param assetId ID that defines asset look and feel /// @param price asset price event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price); function implementsERC721() public pure returns (bool) { return true; } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721. /// @param _interfaceID interface signature ID function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Checks if a given address is the current owner of a particular Asset. /// @param _claimant the address we are validating against. /// @param _tokenId asset UniqueId, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.ownerOf(_tokenId) == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _claimant the address we are confirming asset is approved for. /// @param _tokenId asset UniqueId, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.approvedFor(_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 Assets on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ethernautsStorage.approve(_tokenId, _approved); } /// @notice Returns the number of Assets 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 ethernautsStorage.balanceOf(_owner); } /// @dev Required for ERC-721 compliance. /// @notice Transfers a Asset to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Ethernauts specifically) or your Asset may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Asset to transfer. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets // (except very briefly after it is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the storage contract to prevent accidental // misuse. Auction or Upgrade contracts should only take ownership of assets // through the allow + transferFrom flow. require(_to != address(ethernautsStorage)); // You can only send your own asset. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. ethernautsStorage.transfer(msg.sender, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Grant another address the right to transfer a specific Asset 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 Asset that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) external 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 Asset 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 Asset to be transferred. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function _transferFrom( address _from, address _to, uint256 _tokenId ) internal { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets (except for used assets). require(_owns(_from, _tokenId)); // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). ethernautsStorage.transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Transfer a Asset 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 Asset to be transfered. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { _transferFrom(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. function takeOwnership(uint256 _tokenId) public { address _from = ethernautsStorage.ownerOf(_tokenId); // Safety check to prevent against an unexpected 0x0 default. require(_from != address(0)); _transferFrom(_from, msg.sender, _tokenId); } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return ethernautsStorage.totalSupply(); } /// @notice Returns owner of a given Asset(Token). /// @param _tokenId Token ID to get owner. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ethernautsStorage.ownerOf(_tokenId); require(owner != address(0)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createNewAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats ) external onlyCLevel returns (uint256) { // owner must be sender require(_owner != address(0)); uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, 0, 0 ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice verify if token is in exploration time /// @param _tokenId The Token ID that can be upgraded function isExploring(uint256 _tokenId) public view returns (bool) { uint256 cooldown; uint64 cooldownEndBlock; (,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId); return (cooldown > now) || (cooldownEndBlock > uint64(block.number)); } } /// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts /// @author Ethernatus - Fernando Pauer contract EthernautsLogic is EthernautsOwnership { // Set in case the logic contract is broken and an upgrade is required address public newContractAddress; /// @dev Constructor function EthernautsLogic() public { // the creator of the contract is the initial CEO, COO, CTO ceoAddress = msg.sender; ctoAddress = msg.sender; cooAddress = msg.sender; oracleAddress = msg.sender; // Starts paused. paused = true; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCTO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @dev set a new reference to the NFT ownership contract /// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage. function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(ethernautsStorage != address(0)); require(newContractAddress == address(0)); // require this contract to have access to storage contract require(ethernautsStorage.contractsGrantedAccess(address(this)) == true); // Actually unpause the contract. super.unpause(); } // @dev Allows the COO to capture the balance available to the contract. function withdrawBalances(address _to) public onlyCLevel { _to.transfer(this.balance); } /// return current contract balance function getBalance() public view onlyCLevel returns (uint256) { return this.balance; } } /// @title The facet of the Ethernauts Explore contract that send a ship to explore the deep space. /// @notice An owned ship can be send on an expedition. Exploration takes time // and will always result in “success”. This means the ship can never be destroyed // and always returns with a collection of loot. The degree of success is dependent // on different factors as sector stats, gamma ray burst number and ship stats. // While the ship is exploring it cannot be acted on in any way until the expedition completes. // After the ship returns from an expedition the user is then rewarded with a number of objects (assets). /// @author Ethernatus - Fernando Pauer contract EthernautsExplore is EthernautsLogic { /// @dev Delegate constructor to Nonfungible contract. function EthernautsExplore() public EthernautsLogic() {} /*** EVENTS ***/ /// emit signal to anyone listening in the universe event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time); event Result(uint256 shipId, uint256 sectorID); /*** CONSTANTS ***/ uint8 constant STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255 // @dev Sanity check that allows us to ensure that we are pointing to the // right explore contract in our EthernautsCrewMember(address _CExploreAddress) call. bool public isEthernautsExplore = true; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; uint256 public TICK_TIME = 15; // time is always in minutes // exploration fee uint256 public percentageCut = 90; int256 public SPEED_STAT_MAX = 30; int256 public RANGE_STAT_MAX = 20; int256 public MIN_TIME_EXPLORE = 60; int256 public MAX_TIME_EXPLORE = 2160; int256 public RANGE_SCALE = 2; /// @dev Sector stats enum SectorStats {Size, Threat, Difficulty, Slots} /// @dev hold all ships in exploration uint256[] explorers; /// @dev A mapping from Ship token to the exploration index. mapping (uint256 => uint256) public tokenIndexToExplore; /// @dev A mapping from Asset UniqueIDs to the sector token id. mapping (uint256 => uint256) public tokenIndexToSector; /// @dev A mapping from exploration index to the crew token id. mapping (uint256 => uint256) public exploreIndexToCrew; /// @dev A mission counter for crew. mapping (uint256 => uint16) public missions; /// @dev A mapping from Owner Cut (wei) to the sector token id. mapping (uint256 => uint256) public sectorToOwnerCut; mapping (uint256 => uint256) public sectorToOracleFee; /// @dev Get a list of ship exploring our universe function getExplorerList() public view returns( uint256[3][] ) { uint256[3][] memory tokens = new uint256[3][](50); uint256 index = 0; for(uint256 i = 0; i < explorers.length && index < 50; i++) { if (explorers[i] > 0) { tokens[index][0] = explorers[i]; tokens[index][1] = tokenIndexToSector[explorers[i]]; tokens[index][2] = exploreIndexToCrew[i]; index++; } } if (index == 0) { // Return an empty array return new uint256[3][](0); } else { return tokens; } } /// @dev Get a list of ship exploring our universe /// @param _shipTokenId The Token ID that represents a ship function getIndexByShip(uint256 _shipTokenId) public view returns( uint256 ) { for(uint256 i = 0; i < explorers.length; i++) { if (explorers[i] == _shipTokenId) { return i; } } return 0; } function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel { sectorToOwnerCut[_sectorId] = _ownerCut; } function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel { sectorToOracleFee[_sectorId] = _oracleFee; } function setTickTime(uint256 _tickTime) external onlyCLevel { TICK_TIME = _tickTime; } function setPercentageCut(uint256 _percentageCut) external onlyCLevel { percentageCut = _percentageCut; } function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel { missions[_tokenId] = _total; } /// @notice Explore a sector with a defined ship. Sectors contain a list of Objects that can be given to the players /// when exploring. Each entry has a Drop Rate and are sorted by Sector ID and Drop rate. /// The drop rate is a whole number between 0 and 1,000,000. 0 is 0% and 1,000,000 is 100%. /// Every time a Sector is explored a random number between 0 and 1,000,000 is calculated for each available Object. /// If the final result is lower than the Drop Rate of the Object, that Object will be rewarded to the player once /// Exploration is complete. Only 1 to 5 Objects maximum can be dropped during one exploration. /// (FUTURE VERSIONS) The final number will be affected by the user’s Ship Stats. /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused { // charge a fee for each exploration when the results are ready require(msg.value >= sectorToOwnerCut[_sectorTokenId]); // check if Asset is a ship or not require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship))); // check if _sectorTokenId is a sector or not require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector))); // Ensure the Ship is in available state, otherwise it cannot explore require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available))); // ship could not be in exploration require(tokenIndexToExplore[_shipTokenId] == 0); require(!isExploring(_shipTokenId)); // check if explorer is ship owner require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId)); // check if owner sector is not empty address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId); // check if there is a crew and validating crew member if (_crewTokenId > 0) { // crew member should not be in exploration require(!isExploring(_crewTokenId)); // check if Asset is a crew or not require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember))); // check if crew member is same owner require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId)); } /// store exploration data tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1; tokenIndexToSector[_shipTokenId] = _sectorTokenId; uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId); uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId); // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId; missions[_crewTokenId]++; //// grab crew stats and merge with ship uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId); _shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)]; _shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)]; if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT; } if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT; } } /// set exploration time uint256 time = uint256(_explorationTime( _shipStats[uint256(ShipStats.Range)], _shipStats[uint256(ShipStats.Speed)], _sectorStats[uint256(SectorStats.Size)] )); // exploration time in minutes converted to seconds time *= 60; uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number); ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock); // check if there is a crew store data and set crew exploration time if (_crewTokenId > 0) { /// store crew exploration time ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock); } // to avoid mistakes and charge unnecessary extra fees uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]); uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId]; /// emit signal to anyone listening in the universe Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time); // keeping oracle accounts with balance oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]); // paying sector owner sectorOwner.transfer(payment); // send excess back to explorer msg.sender.transfer(feeExcess); } /// @notice Exploration is complete and at most 10 Objects will return during one exploration. /// @param _shipTokenId The Token ID that represents a ship and can explore /// @param _sectorTokenId The Token ID that represents a sector and can be explored /// @param _IDs that represents a object returned from exploration /// @param _attributes that represents attributes for each object returned from exploration /// @param _stats that represents all stats for each object returned from exploration function explorationResults( uint256 _shipTokenId, uint256 _sectorTokenId, uint16[10] _IDs, uint8[10] _attributes, uint8[STATS_SIZE][10] _stats ) external onlyOracle { uint256 cooldown; uint64 cooldownEndBlock; uint256 builtBy; (,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId); address owner = ethernautsStorage.ownerOf(_shipTokenId); require(owner != address(0)); /// create objects returned from exploration uint256 i = 0; for (i = 0; i < 10 && _IDs[i] > 0; i++) { _buildAsset( _sectorTokenId, owner, 0, _IDs[i], uint8(AssetCategory.Object), uint8(_attributes[i]), _stats[i], cooldown, cooldownEndBlock ); } // to guarantee at least 1 result per exploration require(i > 0); /// remove from explore list explorers[tokenIndexToExplore[_shipTokenId]] = 0; delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; /// emit signal to anyone listening in the universe Result(_shipTokenId, _sectorTokenId); } /// @notice Cancel ship exploration in case it get stuck /// @param _shipTokenId The Token ID that represents a ship and can explore function cancelExplorationByShip( uint256 _shipTokenId ) external onlyCLevel { uint256 index = tokenIndexToExplore[_shipTokenId]; if (index > 0) { /// remove from explore list explorers[index] = 0; if (exploreIndexToCrew[index] > 0) { delete exploreIndexToCrew[index]; } } delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; } /// @notice Cancel exploration in case it get stuck /// @param _index The exploration position that represents a exploring ship function cancelExplorationByIndex( uint256 _index ) external onlyCLevel { uint256 shipId = explorers[_index]; /// remove from exploration list explorers[_index] = 0; if (shipId > 0) { delete tokenIndexToExplore[shipId]; delete tokenIndexToSector[shipId]; } if (exploreIndexToCrew[_index] > 0) { delete exploreIndexToCrew[_index]; } } /// @notice Add exploration in case contract needs to be add trxs from previous contract /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function addExplorationByShip( uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId ) external onlyCLevel whenPaused { uint256 index = explorers.push(_shipTokenId) - 1; /// store exploration data tokenIndexToExplore[_shipTokenId] = index; tokenIndexToSector[_shipTokenId] = _sectorTokenId; // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[index] = _crewTokenId; missions[_crewTokenId]++; } ethernautsStorage.setAssetCooldown(_shipTokenId, now, uint64(block.number)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown see Asset Struct description /// @param _cooldownEndBlock see Asset Struct description function _buildAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) private returns (uint256) { uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, _cooldown, _cooldownEndBlock ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice Exploration Time: The time it takes to explore a Sector is dependent on the Sector Size /// along with the Ship’s Range and Speed. /// @param _shipRange ship range /// @param _shipSpeed ship speed /// @param _sectorSize sector size function _explorationTime( uint8 _shipRange, uint8 _shipSpeed, uint8 _sectorSize ) private view returns (int256) { int256 minToExplore = 0; minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1; minToExplore = -72 * minToExplore; minToExplore += MAX_TIME_EXPLORE; uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX)); uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE); int256 minExplore = (minToExplore - MIN_TIME_EXPLORE); minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange)); minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10); minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE); return minToExplore; } /// @notice calcs a perc without float or double :( function fraction(int256 _subject, int256 _numerator, int256 _denominator) private pure returns (int256) { int256 division = _subject * _numerator - _subject * _denominator; int256 total = _subject * _denominator + division; return total / _denominator; } /// @notice Any C-level can fix how many seconds per blocks are currently observed. /// @param _secs The seconds per block function setSecondsPerBlock(uint256 _secs) external onlyCLevel { require(_secs > 0); secondsPerBlock = _secs; } }
remove from explore list
explorers[tokenIndexToExplore[_shipTokenId]] = 0;
1,044,233
[ 1, 4479, 628, 15233, 266, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 22991, 280, 414, 63, 2316, 1016, 774, 2966, 383, 266, 63, 67, 3261, 1345, 548, 13563, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import {IERC20, SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import {IMintableERC20} from './IMintableERC20.sol'; /** * @title TokenDistributor * @notice It handles the distribution of X2Y2 token. * It auto-adjusts block rewards over a set number of periods. */ contract TokenDistributor is ReentrancyGuard { using SafeERC20 for IERC20; using SafeERC20 for IMintableERC20; struct StakingPeriod { uint256 rewardPerBlockForStaking; uint256 rewardPerBlockForOthers; uint256 periodLengthInBlock; } struct UserInfo { uint256 amount; // Amount of staked tokens provided by user uint256 rewardDebt; // Reward debt } // Precision factor for calculating rewards uint256 public constant PRECISION_FACTOR = 10**12; IMintableERC20 public immutable x2y2Token; address public immutable tokenSplitter; // Number of reward periods uint256 public immutable NUMBER_PERIODS; // Block number when rewards start uint256 public immutable START_BLOCK; // Accumulated tokens per share uint256 public accTokenPerShare; // Current phase for rewards uint256 public currentPhase; // Block number when rewards end uint256 public endBlock; // Block number of the last update uint256 public lastRewardBlock; // Tokens distributed per block for other purposes (team + treasury + trading rewards) uint256 public rewardPerBlockForOthers; // Tokens distributed per block for staking uint256 public rewardPerBlockForStaking; // Total amount staked uint256 public totalAmountStaked; mapping(uint256 => StakingPeriod) public stakingPeriod; mapping(address => UserInfo) public userInfo; event Compound(address indexed user, uint256 harvestedAmount); event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount); event NewRewardsPerBlock( uint256 indexed currentPhase, uint256 startBlock, uint256 rewardPerBlockForStaking, uint256 rewardPerBlockForOthers ); event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount); /** * @notice Constructor * @param _x2y2Token token address * @param _tokenSplitter token splitter contract address (for team and trading rewards) * @param _startBlock start block for reward program * @param _rewardsPerBlockForStaking array of rewards per block for staking * @param _rewardsPerBlockForOthers array of rewards per block for other purposes (team + treasury + trading rewards) * @param _periodLengthesInBlocks array of period lengthes * @param _numberPeriods number of periods with different rewards/lengthes (e.g., if 3 changes --> 4 periods) */ constructor( address _x2y2Token, address _tokenSplitter, uint256 _startBlock, uint256[] memory _rewardsPerBlockForStaking, uint256[] memory _rewardsPerBlockForOthers, uint256[] memory _periodLengthesInBlocks, uint256 _numberPeriods ) { require( (_periodLengthesInBlocks.length == _numberPeriods) && (_rewardsPerBlockForStaking.length == _numberPeriods) && (_rewardsPerBlockForStaking.length == _numberPeriods), 'Distributor: Lengthes must match numberPeriods' ); // 1. Operational checks for supply uint256 nonCirculatingSupply = IMintableERC20(_x2y2Token).SUPPLY_CAP() - IMintableERC20(_x2y2Token).totalSupply(); uint256 amountTokensToBeMinted; for (uint256 i = 0; i < _numberPeriods; i++) { amountTokensToBeMinted += (_rewardsPerBlockForStaking[i] * _periodLengthesInBlocks[i]) + (_rewardsPerBlockForOthers[i] * _periodLengthesInBlocks[i]); stakingPeriod[i] = StakingPeriod({ rewardPerBlockForStaking: _rewardsPerBlockForStaking[i], rewardPerBlockForOthers: _rewardsPerBlockForOthers[i], periodLengthInBlock: _periodLengthesInBlocks[i] }); } require( amountTokensToBeMinted == nonCirculatingSupply, 'Distributor: Wrong reward parameters' ); // 2. Store values x2y2Token = IMintableERC20(_x2y2Token); tokenSplitter = _tokenSplitter; rewardPerBlockForStaking = _rewardsPerBlockForStaking[0]; rewardPerBlockForOthers = _rewardsPerBlockForOthers[0]; START_BLOCK = _startBlock; endBlock = _startBlock + _periodLengthesInBlocks[0]; NUMBER_PERIODS = _numberPeriods; // Set the lastRewardBlock as the startBlock lastRewardBlock = _startBlock; } /** * @notice Deposit staked tokens and compounds pending rewards * @param amount amount to deposit (in X2Y2) */ function deposit(uint256 amount) external nonReentrant { require(amount > 0, 'Deposit: Amount must be > 0'); require(block.number >= START_BLOCK, 'Deposit: Not started yet'); // Update pool information _updatePool(); // Transfer X2Y2 tokens to this contract x2y2Token.safeTransferFrom(msg.sender, address(this), amount); uint256 pendingRewards; // If not new deposit, calculate pending rewards (for auto-compounding) if (userInfo[msg.sender].amount > 0) { pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; } // Adjust user information userInfo[msg.sender].amount += (amount + pendingRewards); userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; // Increase totalAmountStaked totalAmountStaked += (amount + pendingRewards); emit Deposit(msg.sender, amount, pendingRewards); } /** * @notice Compound based on pending rewards */ function harvestAndCompound() external nonReentrant { // Update pool information _updatePool(); // Calculate pending rewards uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; // Return if no pending rewards if (pendingRewards == 0) { // It doesn't throw revertion (to help with the fee-sharing auto-compounding contract) return; } // Adjust user amount for pending rewards userInfo[msg.sender].amount += pendingRewards; // Adjust totalAmountStaked totalAmountStaked += pendingRewards; // Recalculate reward debt based on new user amount userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; emit Compound(msg.sender, pendingRewards); } /** * @notice Update pool rewards */ function updatePool() external nonReentrant { _updatePool(); } /** * @notice Withdraw staked tokens and compound pending rewards * @param amount amount to withdraw */ function withdraw(uint256 amount) external nonReentrant { require( (userInfo[msg.sender].amount >= amount) && (amount > 0), 'Withdraw: Amount must be > 0 or lower than user balance' ); // Update pool _updatePool(); // Calculate pending rewards uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; // Adjust user information userInfo[msg.sender].amount = userInfo[msg.sender].amount + pendingRewards - amount; userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; // Adjust total amount staked totalAmountStaked = totalAmountStaked + pendingRewards - amount; // Transfer X2Y2 tokens to the sender x2y2Token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount, pendingRewards); } /** * @notice Withdraw all staked tokens and collect tokens */ function withdrawAll() external nonReentrant { require(userInfo[msg.sender].amount > 0, 'Withdraw: Amount must be > 0'); // Update pool _updatePool(); // Calculate pending rewards and amount to transfer (to the sender) uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; uint256 amountToTransfer = userInfo[msg.sender].amount + pendingRewards; // Adjust total amount staked totalAmountStaked = totalAmountStaked - userInfo[msg.sender].amount; // Adjust user information userInfo[msg.sender].amount = 0; userInfo[msg.sender].rewardDebt = 0; // Transfer X2Y2 tokens to the sender x2y2Token.safeTransfer(msg.sender, amountToTransfer); emit Withdraw(msg.sender, amountToTransfer, pendingRewards); } /** * @notice Calculate pending rewards for a user * @param user address of the user * @return Pending rewards */ function calculatePendingRewards(address user) external view returns (uint256) { if ((block.number > lastRewardBlock) && (totalAmountStaked != 0)) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; uint256 adjustedEndBlock = endBlock; uint256 adjustedCurrentPhase = currentPhase; // Check whether to adjust multipliers and reward per block while ( (block.number > adjustedEndBlock) && (adjustedCurrentPhase < (NUMBER_PERIODS - 1)) ) { // Update current phase adjustedCurrentPhase++; // Update rewards per block uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase] .rewardPerBlockForStaking; // Calculate adjusted block number uint256 previousEndBlock = adjustedEndBlock; // Update end block adjustedEndBlock = previousEndBlock + stakingPeriod[adjustedCurrentPhase].periodLengthInBlock; // Calculate new multiplier uint256 newMultiplier = (block.number <= adjustedEndBlock) ? (block.number - previousEndBlock) : stakingPeriod[adjustedCurrentPhase].periodLengthInBlock; // Adjust token rewards for staking tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking); } uint256 adjustedTokenPerShare = accTokenPerShare + (tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked; return (userInfo[user].amount * adjustedTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt; } else { return (userInfo[user].amount * accTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt; } } /** * @notice Update reward variables of the pool */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (totalAmountStaked == 0) { lastRewardBlock = block.number; return; } // Calculate multiplier uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); // Calculate rewards for staking and others uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers; // Check whether to adjust multipliers and reward per block while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) { // Update rewards per block _updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock; // Adjust the end block endBlock += stakingPeriod[currentPhase].periodLengthInBlock; // Adjust multiplier to cover the missing periods with other lower inflation schedule uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number); // Adjust token rewards tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking); tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers); } // Mint tokens only if token rewards for staking are not null if (tokenRewardForStaking > 0) { // It allows protection against potential issues to prevent funds from being locked bool mintStatus = x2y2Token.mint(address(this), tokenRewardForStaking); if (mintStatus) { accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); } x2y2Token.mint(tokenSplitter, tokenRewardForOthers); } // Update last reward block only if it wasn't updated after or at the end block if (lastRewardBlock <= endBlock) { lastRewardBlock = block.number; } } /** * @notice Update rewards per block * @dev Rewards are halved by 2 (for staking + others) */ function _updateRewardsPerBlock(uint256 _newStartBlock) internal { // Update current phase currentPhase++; // Update rewards per block rewardPerBlockForStaking = stakingPeriod[currentPhase].rewardPerBlockForStaking; rewardPerBlockForOthers = stakingPeriod[currentPhase].rewardPerBlockForOthers; emit NewRewardsPerBlock( currentPhase, _newStartBlock, rewardPerBlockForStaking, rewardPerBlockForOthers ); } /** * @notice Return reward multiplier over the given "from" to "to" block. * @param from block to start calculating reward * @param to block to finish calculating reward * @return the multiplier for the period */ function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { if (to <= endBlock) { return to - from; } else if (from >= endBlock) { return 0; } else { return endBlock - from; } } } // 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 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IMintableERC20 is IERC20 { function SUPPLY_CAP() external view returns (uint256); function mint(address account, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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); } } } }
Tokens distributed per block for staking
uint256 public rewardPerBlockForStaking;
376,710
[ 1, 5157, 16859, 1534, 1203, 364, 384, 6159, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5034, 1071, 19890, 2173, 1768, 1290, 510, 6159, 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 ]
pragma solidity ^0.4.2; // CERTIFICADOS EMITIDOS POR UM CERTIFICADOR contract EnergyCert { address public certifier; // emissor do certificado address public owner; // dono do certificado uint16 public availableMwh; // quantidade de MWH disponíveis uint16 public usedMwh; // quantidade de MWH usados // Criação de um novo certificado function EnergyCert(address _certifier, address _owner, uint16 availableMwh, uint16 _usedMwh) { certifier = _certifier; // é setado na criação e nunca muda owner = _owner; // é setado na criação e nunca muda availableMwh = availableMwh; usedMwh = 0; } // só continua se requerente for o dono do certificado modifier isOwner() { require( owner == msg.sender ) _; } // transfere MWH disponíveis para usados function use(uint16 mwh) isOwner { require( mwh <= availableMwh ); availableMwh -= mwh; usedMwh += mwh; } // remove o certificado para a criação de um novo function remove() isOwner { selfdestruct(owner); } } // FÁBRICA DE CERTIFICADOS POR UM CERTIFICADOR contract EnergyCertFactory { address public certifier; // criador da fábrica e emissor de novos certificados // cria uma fábria de certificados e emite a primeira quantidade de MWH certificada function EnergyCertFactory(uint16 mwh) public { certifier = msg.sender; // seta o certificador que nunca muda if(mwh > 0) { new EnergyCert(certifier, certifier, mwh, 0); } } // Continua apenas se o requerent for o certificador modifier isCertifier() { require( certifier == msg.sender ) _; } // Emite novo certificado function issue(uint mwh) isCertifier { if(mwh > 0) { new EnergyCert(certifier, certifier, mwh, 0); } } // transferir para alguém uma quantidade de MWH certificada function transfer(address certificationAddr, address to, uint16 mwh) public returns (bool success) { EnergyCert cert = EnergyCert(certificationAddr); // referencia do certificado if ( cert.owner == msg.sender ) // o dono do certificado deve ser o requerente return false; if ( to == 0x0 ) // o recebedor deve existir return false; if ( mwh == 0 ) // não tem porque transferir 0 return false; if( mwh > cert.availableMwh ) // o valor a ser transferido deve ser maior que o valor disponível return false; // guarda os valores do certificado atual available = cert.availableMwh; used = cert.usedMwh; cert.remove(); // destrói certificado antigo new EnergyCert(certifier, msg.sender, available - mwh, used); // cria um certificado novo deduzindo que foi transferido new EnergyCert(certifier, to, mwh, 0); // cria um certificado novo para o recebedor com a quantidade indicada return true; } }
criador da fábrica e emissor de novos certificados
address public certifier;
13,122,005
[ 1, 22203, 23671, 5248, 284, 132, 99, 70, 1512, 69, 425, 801, 1054, 280, 443, 1158, 90, 538, 276, 2303, 18739, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 3320, 1251, 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, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/badger/IBadgerGeyser.sol"; import "interfaces/sushi/ISushiChef.sol"; import "interfaces/uniswap/IUniswapPair.sol"; import "interfaces/sushi/IxSushi.sol"; import "interfaces/badger/IController.sol"; import "interfaces/badger/IMintr.sol"; import "interfaces/badger/IStrategy.sol"; import "interfaces/badger/ISettV4.sol"; import "interfaces/convex/IBooster.sol"; import "interfaces/convex/CrvDepositor.sol"; import "interfaces/convex/IBaseRewardsPool.sol"; import "interfaces/convex/ICvxRewardsPool.sol"; import "../BaseStrategySwapper.sol"; import "../../libraries/CurveSwapper.sol"; import "../../libraries/UniswapSwapper.sol"; import "../../libraries/TokenSwapPathRegistry.sol"; /* === Deposit === Deposit & Stake underlying asset into appropriate convex vault (deposit + stake is atomic) === Tend === == Stage 1: Realize gains from all positions == Harvest CRV and CVX from core vault rewards pool Harvest CVX and SUSHI from CVX/ETH LP Harvest CVX and SUSHI from cvxCRV/CRV LP Harvested coins: CRV CVX SUSHI == Stage 2: Deposit all gains into staked positions == Zap all CRV -> cvxCRV/CRV Zap all CVX -> CVX/ETH Stake Sushi Position coins: cvxCRV/CRV CVX/ETH xSushi These position coins will be distributed on harvest Changelog: V1.1 * Implemented the _exchange function from the CurveSwapper library to perform the CRV -> cvxCRV and vice versa swaps through curve instead of Sushiswap. * It now swaps 3CRV into CRV instead of cvxCRV. If enough is aquired, it swaps this CRV for wBTC directly and, if not, it swaps some cvxCRV for CRV to compensate. * Removed some unused functions and variables such as the `addExtraRewardsToken` and `removeExtraRewardsToken` functions as well as the obsolete swapping paths. */ contract StrategyConvexStakingOptimizer is BaseStrategy, CurveSwapper, UniswapSwapper, TokenSwapPathRegistry { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // ===== Token Registry ===== address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant cvxCrv = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant threeCrv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; IERC20Upgradeable public constant wbtcToken = IERC20Upgradeable(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20Upgradeable public constant crvToken = IERC20Upgradeable(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20Upgradeable public constant cvxToken = IERC20Upgradeable(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); IERC20Upgradeable public constant cvxCrvToken = IERC20Upgradeable(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7); IERC20Upgradeable public constant usdcToken = IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20Upgradeable public constant threeCrvToken = IERC20Upgradeable(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); // ===== Convex Registry ===== CrvDepositor public constant crvDepositor = CrvDepositor(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae); // Convert CRV -> cvxCRV IBooster public constant booster = IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); IBaseRewardsPool public baseRewardsPool; IBaseRewardsPool public constant cvxCrvRewardsPool = IBaseRewardsPool(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e); ICvxRewardsPool public constant cvxRewardsPool = ICvxRewardsPool(0xCF50b810E57Ac33B91dCF525C6ddd9881B139332); ISushiChef public constant convexMasterChef = ISushiChef(0x5F465e9fcfFc217c5849906216581a657cd60605); address public constant threeCrvSwap = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; uint256 public constant cvxCRV_CRV_SLP_Pid = 0; uint256 public constant CVX_ETH_SLP_Pid = 1; uint256 public constant MAX_UINT_256 = uint256(-1); uint256 public pid; address public badgerTree; ISettV4 public cvxHelperVault; ISettV4 public cvxCrvHelperVault; /** The default conditions for a rewards token are: - Collect rewards token - Distribute 100% via Tree to users === Harvest Config === - autoCompoundingBps: Sell this % of rewards for underlying asset. - autoCompoundingPerfFee: Of the auto compounded portion, take this % as a performance fee. - treeDistributionPerfFee: Of the remaining portion (everything not distributed or converted via another mehcanic is distributed via the tree), take this % as a performance fee. === Tend Config === - tendConvertTo: On tend, convert some of this token into another asset. By default with value as address(0), skip this step. - tendConvertBps: Convert this portion of balance into another asset. */ struct RewardTokenConfig { uint256 autoCompoundingBps; uint256 autoCompoundingPerfFee; uint256 treeDistributionPerfFee; address tendConvertTo; uint256 tendConvertBps; } struct CurvePoolConfig { address swap; uint256 wbtcPosition; uint256 numElements; } EnumerableSetUpgradeable.AddressSet internal extraRewards; // Tokens other than CVX and cvxCRV to process as rewards mapping(address => RewardTokenConfig) public rewardsTokenConfig; CurvePoolConfig public curvePool; uint256 public autoCompoundingBps; uint256 public autoCompoundingPerformanceFeeGovernance; uint256 public constant crvCvxCrvPoolIndex = 2; event TreeDistribution(address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp); event PerformanceFeeGovernance( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeStrategist( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event WithdrawState(uint256 toWithdraw, uint256 preWant, uint256 postWant, uint256 withdrawn); struct HarvestData { uint256 cvxCrvHarvested; uint256 cvxHarvsted; } struct TendData { uint256 crvTended; uint256 cvxTended; uint256 cvxCrvTended; } struct TokenSwapData { address tokenIn; uint256 totalSold; uint256 wantGained; } event TendState(uint256 crvTended, uint256 cvxTended, uint256 cvxCrvTended); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[4] memory _wantConfig, uint256 _pid, uint256[3] memory _feeConfig, CurvePoolConfig memory _curvePool ) public initializer whenNotPaused { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); want = _wantConfig[0]; badgerTree = _wantConfig[1]; cvxHelperVault = ISettV4(_wantConfig[2]); cvxCrvHelperVault = ISettV4(_wantConfig[3]); pid = _pid; // Core staking pool ID IBooster.PoolInfo memory poolInfo = booster.poolInfo(pid); baseRewardsPool = IBaseRewardsPool(poolInfo.crvRewards); performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; // Approvals: Staking Pools IERC20Upgradeable(want).approve(address(booster), MAX_UINT_256); cvxToken.approve(address(cvxRewardsPool), MAX_UINT_256); cvxCrvToken.approve(address(cvxCrvRewardsPool), MAX_UINT_256); // Approvals: CRV -> cvxCRV converter crvToken.approve(address(crvDepositor), MAX_UINT_256); curvePool = CurvePoolConfig(_curvePool.swap, _curvePool.wbtcPosition, _curvePool.numElements); // Set Swap Paths address[] memory path = new address[](3); path[0] = cvx; path[1] = weth; path[2] = wbtc; _setTokenSwapPath(cvx, wbtc, path); _initializeApprovals(); autoCompoundingBps = 2000; autoCompoundingPerformanceFeeGovernance = 5000; } /// ===== Permissioned Functions ===== function setPid(uint256 _pid) external { _onlyGovernance(); pid = _pid; // LP token pool ID } function setAutoCompoundingBps(uint256 _bps) external { _onlyGovernance(); autoCompoundingBps = _bps; } function setAutoCompoundingPerformanceFeeGovernance(uint256 _bps) external { _onlyGovernance(); autoCompoundingPerformanceFeeGovernance = _bps; } function initializeApprovals() external { _onlyGovernance(); _initializeApprovals(); } function setCurvePoolSwap(address _swap) external { _onlyGovernance(); curvePool.swap = _swap; } function _initializeApprovals() internal { cvxToken.approve(address(cvxHelperVault), MAX_UINT_256); cvxCrvToken.approve(address(cvxCrvHelperVault), MAX_UINT_256); } /// ===== View Functions ===== function version() external pure returns (string memory) { return "1.1"; } function getName() external override pure returns (string memory) { return "StrategyConvexStakingOptimizer"; } function balanceOfPool() public override view returns (uint256) { return baseRewardsPool.balanceOf(address(this)); } function getProtectedTokens() public override view returns (address[] memory) { address[] memory protectedTokens = new address[](4); protectedTokens[0] = want; protectedTokens[1] = crv; protectedTokens[2] = cvx; protectedTokens[3] = cvxCrv; return protectedTokens; } function isTendable() public override view returns (bool) { return true; } /// ===== Internal Core Implementations ===== function _onlyNotProtectedTokens(address _asset) internal override { require(address(want) != _asset, "want"); require(address(crv) != _asset, "crv"); require(address(cvx) != _asset, "cvx"); require(address(cvxCrv) != _asset, "cvxCrv"); } /// @dev Deposit Badger into the staking contract function _deposit(uint256 _want) internal override { // Deposit all want in core staking pool booster.deposit(pid, _want, true); } /// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards function _withdrawAll() internal override { baseRewardsPool.withdrawAndUnwrap(balanceOfPool(), false); // Note: All want is automatically withdrawn outside this "inner hook" in base strategy function } /// @dev Withdraw want from staking rewards, using earnings first function _withdrawSome(uint256 _amount) internal override returns (uint256) { // Get idle want in the strategy uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this)); // If we lack sufficient idle want, withdraw the difference from the strategy position if (_preWant < _amount) { uint256 _toWithdraw = _amount.sub(_preWant); baseRewardsPool.withdrawAndUnwrap(_toWithdraw, false); } // Confirm how much want we actually end up with uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this)); // Return the actual amount withdrawn if less than requested uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount); emit WithdrawState(_amount, _preWant, _postWant, _withdrawn); return _withdrawn; } function _tendGainsFromPositions() internal { // Harvest CRV, CVX, cvxCRV, 3CRV, and extra rewards tokens from staking positions // Note: Always claim extras baseRewardsPool.getReward(address(this), true); if (cvxCrvRewardsPool.earned(address(this)) > 0) { cvxCrvRewardsPool.getReward(address(this), true); } if (cvxRewardsPool.earned(address(this)) > 0) { cvxRewardsPool.getReward(false); } } function patchPaths() external { _onlyGovernance(); address[] memory path = new address[](3); path[0] = usdc; path[1] = weth; path[2] = crv; _setTokenSwapPath(usdc, crv, path); path = new address[](3); path[0] = crv; path[1] = weth; path[2] = wbtc; _setTokenSwapPath(crv, wbtc, path); } /// @notice The more frequent the tend, the higher returns will be function tend() external whenNotPaused returns (TendData memory) { _onlyAuthorizedActors(); TendData memory tendData; // 1. Harvest gains from positions _tendGainsFromPositions(); // Track harvested coins, before conversion tendData.crvTended = crvToken.balanceOf(address(this)); // 2. Convert CRV -> cvxCRV if (tendData.crvTended > 0) { _exchange(crv, cvxCrv, tendData.crvTended, crvCvxCrvPoolIndex, true); } // Track harvested + converted coins tendData.cvxCrvTended = cvxCrvToken.balanceOf(address(this)); tendData.cvxTended = cvxToken.balanceOf(address(this)); // 3. Stake all cvxCRV if (tendData.cvxCrvTended > 0) { cvxCrvRewardsPool.stake(tendData.cvxCrvTended); } // 4. Stake all CVX if (tendData.cvxTended > 0) { cvxRewardsPool.stake(cvxToken.balanceOf(address(this))); } emit Tend(0); emit TendState(tendData.crvTended, tendData.cvxTended, tendData.cvxCrvTended); return tendData; } // No-op until we optimize harvesting strategy. Auto-compouding is key. function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; uint256 idleWant = IERC20Upgradeable(want).balanceOf(address(this)); uint256 totalWantBefore = balanceOf(); // TODO: Harvest details still under constructuion. It's being designed to optimize yield while still allowing on-demand access to profits for users. // 1. Withdraw accrued rewards from staking positions (claim unclaimed positions as well) baseRewardsPool.getReward(address(this), true); uint256 cvxCrvRewardsPoolBalance = cvxCrvRewardsPool.balanceOf(address(this)); if (cvxCrvRewardsPoolBalance > 0) { cvxCrvRewardsPool.withdraw(cvxCrvRewardsPoolBalance, true); } uint256 cvxRewardsPoolBalance = cvxRewardsPool.balanceOf(address(this)); if (cvxRewardsPoolBalance > 0) { cvxRewardsPool.withdraw(cvxRewardsPoolBalance, true); } harvestData.cvxCrvHarvested = cvxCrvToken.balanceOf(address(this)); harvestData.cvxHarvsted = cvxToken.balanceOf(address(this)); // 2. Convert 3CRV -> CRV via USDC uint256 threeCrvBalance = threeCrvToken.balanceOf(address(this)); if (threeCrvBalance > 0) { _remove_liquidity_one_coin(threeCrvSwap, threeCrvBalance, 1, 0); _swapExactTokensForTokens(sushiswap, usdc, usdcToken.balanceOf(address(this)), getTokenSwapPath(usdc, crv)); } // 3. Sell 20% of accured rewards for underlying if (harvestData.cvxCrvHarvested > 0) { uint256 cvxCrvToSell = harvestData.cvxCrvHarvested.mul(autoCompoundingBps).div(MAX_FEE); // NOTE: Assuming any CRV accumulted is only from the above swap uint256 crvBalance = crvToken.balanceOf(address(this)); // NOTE: Asssumes 1:1 CRV/cvxCRV if (cvxCrvToSell > crvBalance) { _exchange(cvxCrv, crv, cvxCrvToSell.sub(crvBalance), crvCvxCrvPoolIndex, true); cvxCrvToSell = crvToken.balanceOf(address(this)); } _swapExactTokensForTokens(sushiswap, crv, cvxCrvToSell, getTokenSwapPath(crv, wbtc)); } // 4. Convert CRV -> cvxCRV uint256 crvBalance = crvToken.balanceOf(address(this)); if (crvBalance > 0) { _exchange(crv, cvxCrv, crvBalance, crvCvxCrvPoolIndex, true); } if (harvestData.cvxHarvsted > 0) { uint256 cvxToSell = harvestData.cvxHarvsted.mul(autoCompoundingBps).div(MAX_FEE); _swapExactTokensForTokens(sushiswap, cvx, cvxToSell, getTokenSwapPath(cvx, wbtc)); } // Process extra rewards tokens // Note: Assumes asset is ultimately swappable on Uniswap for underlying // { // for (uint256 i = 0; i < extraRewards.length(); i=i+1) { // address token = extraRewards.at(i); // RewardTokenConfig memory rewardsConfig = rewardsTokenConfig[token]; // /* // autoCompoundingBps = 30 // autoCompoundingPerfFee = 10000 // treeDistributionPerfFee = 0 // */ // IERC20Upgradeable tokenContract = IERC20Upgradeable(token); // uint256 tokenBalance = tokenContract.balanceOf(address(this)); // // Sell compounding proportion to wbtc // uint256 amountToSell = tokenBalance.mul(rewardsConfig.autoCompoundingBps).div(MAX_FEE); // _swapExactTokensForTokens(uniswap, token, amountToSell, getTokenSwapPath(token, wbtc)); // uint256 wbtcToDeposit = wbtcToken.balanceOf(address(this)); // // TODO: Significant optimization by batching this will other curve deposit // _add_liquidity_single_coin(curvePool.swap, want, wbtc, wbtcToDeposit, curvePool.wbtcPosition, curvePool.numElements, 0); // uint256 wantGained = IERC20Upgradeable(want).balanceOf(address(this)).sub(idleWant); // uint256 autoCompoundedPerformanceFee = wantGained.mul(rewardsConfig.autoCompoundingPerfFee).div(MAX_FEE); // IERC20Upgradeable(want).transfer(IController(controller).rewards(), autoCompoundedPerformanceFee); // emit PerformanceFeeGovernance(IController(controller).rewards(), want, autoCompoundedPerformanceFee, block.number, block.timestamp); // // Distribute remainder to users // uint256 treeRewardBalanceBefore = tokenContract.balanceOf(badgerTree); // uint256 remainingRewardBalance = tokenContract.balanceOf(address(this)); // tokenContract.safeTransfer(badgerTree, remainingRewardBalance); // uint256 treeRewardBalanceAfter = tokenContract.balanceOf(badgerTree); // uint256 treeRewardBalanceGained = treeRewardBalanceAfter.sub(treeRewardBalanceBefore); // emit TreeDistribution(token, treeRewardBalanceGained, block.number, block.timestamp); // } // } // 4. Roll WBTC gained into want position uint256 wbtcToDeposit = wbtcToken.balanceOf(address(this)); if (wbtcToDeposit > 0) { _add_liquidity_single_coin(curvePool.swap, want, wbtc, wbtcToDeposit, curvePool.wbtcPosition, curvePool.numElements, 0); uint256 wantGained = IERC20Upgradeable(want).balanceOf(address(this)).sub(idleWant); // Half of gained want (10% of rewards) are auto-compounded, half of gained want is taken as a performance fee uint256 autoCompoundedPerformanceFee = wantGained.mul(autoCompoundingPerformanceFeeGovernance).div(MAX_FEE); IERC20Upgradeable(want).transfer(IController(controller).rewards(), autoCompoundedPerformanceFee); emit PerformanceFeeGovernance(IController(controller).rewards(), want, autoCompoundedPerformanceFee, block.number, block.timestamp); } // Deposit remaining want (including idle want) into strategy position uint256 wantToDeposited = IERC20Upgradeable(want).balanceOf(address(this)); if (wantToDeposited > 0) { _deposit(wantToDeposited); } // 5. Deposit remaining CVX / cvxCRV rewards into helper vaults and distribute if (harvestData.cvxCrvHarvested > 0) { uint256 cvxCrvToDistribute = cvxCrvToken.balanceOf(address(this)); if (performanceFeeGovernance > 0) { uint256 cvxCrvToGovernance = cvxCrvToDistribute.mul(performanceFeeGovernance).div(MAX_FEE); cvxCrvHelperVault.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), cvxCrv, cvxCrvToGovernance, block.number, block.timestamp); } if (performanceFeeStrategist > 0) { uint256 cvxCrvToStrategist = cvxCrvToDistribute.mul(performanceFeeStrategist).div(MAX_FEE); cvxCrvHelperVault.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, cvxCrv, cvxCrvToStrategist, block.number, block.timestamp); } // TODO: [Optimization] Allow contract to circumvent blockLock to dedup deposit operations uint256 treeHelperVaultBefore = cvxCrvHelperVault.balanceOf(badgerTree); // Deposit remaining to tree after taking fees. uint256 cvxCrvToTree = cvxCrvToken.balanceOf(address(this)); cvxCrvHelperVault.depositFor(badgerTree, cvxCrvToTree); uint256 treeHelperVaultAfter = cvxCrvHelperVault.balanceOf(badgerTree); uint256 treeVaultPositionGained = treeHelperVaultAfter.sub(treeHelperVaultBefore); emit TreeDistribution(address(cvxCrvHelperVault), treeVaultPositionGained, block.number, block.timestamp); } if (harvestData.cvxHarvsted > 0) { uint256 cvxToDistribute = cvxToken.balanceOf(address(this)); if (performanceFeeGovernance > 0) { uint256 cvxToGovernance = cvxToDistribute.mul(performanceFeeGovernance).div(MAX_FEE); cvxHelperVault.depositFor(IController(controller).rewards(), cvxToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), cvx, cvxToGovernance, block.number, block.timestamp); } if (performanceFeeStrategist > 0) { uint256 cvxToStrategist = cvxToDistribute.mul(performanceFeeStrategist).div(MAX_FEE); cvxHelperVault.depositFor(strategist, cvxToStrategist); emit PerformanceFeeStrategist(strategist, cvx, cvxToStrategist, block.number, block.timestamp); } // TODO: [Optimization] Allow contract to circumvent blockLock to dedup deposit operations uint256 treeHelperVaultBefore = cvxHelperVault.balanceOf(badgerTree); // Deposit remaining to tree after taking fees. uint256 cvxToTree = cvxToken.balanceOf(address(this)); cvxHelperVault.depositFor(badgerTree, cvxToTree); uint256 treeHelperVaultAfter = cvxHelperVault.balanceOf(badgerTree); uint256 treeVaultPositionGained = treeHelperVaultAfter.sub(treeHelperVaultBefore); emit TreeDistribution(address(cvxHelperVault), treeVaultPositionGained, block.number, block.timestamp); } uint256 totalWantAfter = balanceOf(); require(totalWantAfter >= totalWantBefore, "harvest-total-want-must-not-decrease"); return harvestData; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @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 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 pragma solidity ^0.6.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.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 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"); } } } // 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IUniswapRouterV2 { function factory() external view 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 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); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IBadgerGeyser { function stake(address) external returns (uint256); function signalTokenLock( address token, uint256 amount, uint256 durationSec, uint256 startTime ) external; function modifyTokenLock( address token, uint256 index, uint256 amount, uint256 durationSec, uint256 startTime ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "interfaces/erc20/IERC20.sol"; // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } interface ISushiChef { // ===== Write ===== function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function updatePool(uint256 _pid) external; // ===== Read ===== function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); function owner() external view returns (address); function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); } //SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IUniswapPair { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } //SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IxSushi { function enter(uint256 _amount) external; function leave(uint256 _shares) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IController { function withdraw(address, uint256) external; function withdrawAll(address) external; function strategies(address) external view returns (address); function approvedStrategies(address, address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function approveStrategy(address, address) external; function setStrategy(address, address) external; function setVault(address, address) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IMintr { function mint(address) external; } // SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function balanceOfPool() external view returns (uint256); function balanceOfWant() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function controller() external returns (address); function governance() external returns (address); function tend() external; function harvest() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface ISettV4 { function token() external view returns (address); function keeper() external view returns (address); function deposit(uint256) external; function depositFor(address, uint256) external; function depositAll() external; function withdraw(uint256) external; function withdrawAll() external; function earn() external; function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getPricePerFullShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; pragma experimental ABIEncoderV2; interface IBooster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); function depositAll(uint256 _pid, bool _stake) external returns (bool); function withdraw(uint256 _pid, uint256 _amount) external returns (bool); function withdrawAll(uint256 _pid) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface CrvDepositor { //deposit crv for cvxCrv //can locking immediately or defer locking to someone else by paying a fee. //while users can choose to lock or defer, this is mostly in place so that //the cvx reward contract isnt costly to claim rewards function deposit(uint256 _amount, bool _lock) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IBaseRewardsPool { //balance function balanceOf(address _account) external view returns (uint256); //withdraw to a convex tokenized deposit function withdraw(uint256 _amount, bool _claim) external returns (bool); function withdrawAll(bool _claim) external; //withdraw directly to curve LP token function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool); //claim rewards function getReward() external returns (bool); //stake a convex tokenized deposit function stake(uint256 _amount) external returns (bool); //stake a convex tokenized deposit for another address(transfering ownership) function stakeFor(address _account, uint256 _amount) external returns (bool); function getReward(address _account, bool _claimExtras) external returns (bool); function rewards(address _account) external view returns (uint256); function earned(address _account) external view returns (uint256); function stakingToken() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface ICvxRewardsPool { //balance function balanceOf(address _account) external view returns (uint256); //withdraw to a convex tokenized deposit function withdraw(uint256 _amount, bool _claim) external; function withdrawAll(bool _claim) external; //withdraw directly to curve LP token function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool); //claim rewards function getReward(bool _stake) external; //stake a convex tokenized deposit function stake(uint256 _amount) external; //stake a convex tokenized deposit for another address(transfering ownership) function stakeFor(address _account, uint256 _amount) external returns (bool); function rewards(address _account) external view returns (uint256); function earned(address _account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/uniswap/IUniswapV2Factory.sol"; import "interfaces/badger/IController.sol"; import "interfaces/badger/IStrategy.sol"; import "../SettAccessControl.sol"; import "./BaseStrategy.sol"; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ abstract contract BaseStrategyMultiSwapper is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router /// @notice Swap specified balance of given token on Uniswap with given path function _swap_uniswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn_uniswap(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthIn_sushiswap(uint256 balance, address[] memory path) internal { IUniswapRouterV2(sushiswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut_uniswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _swapEthOut_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _get_uni_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(uniswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } function _get_sushi_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(sushiswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_sushiswap(address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, sushiswap, _token0Balance); _safeApproveHelper(token1, sushiswap, _token1Balance); IUniswapRouterV2(sushiswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } function _add_max_liquidity_eth_sushiswap(address token0) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _ethBalance = address(this).balance; _safeApproveHelper(token0, sushiswap, _token0Balance); IUniswapRouterV2(sushiswap).addLiquidityETH{value: address(this).balance}(token0, _token0Balance, 0, 0, address(this), block.timestamp); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "interfaces/curve/ICurveFi.sol"; import "interfaces/curve/ICurveExchange.sol"; import "interfaces/curve/ICurveRegistry.sol"; import "./BaseSwapper.sol"; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract CurveSwapper is BaseSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address public constant addressProvider = 0x0000000022D53366457F9d5E68Ec105046FC4383; uint256 public constant registryId = 0; uint256 public constant metaPoolFactoryId = 3; function _exchange( address _from, address _to, uint256 _dx, uint256 _index, bool _isFactoryPool ) internal { address poolRegistry = ICurveRegistryAddressProvider(addressProvider).get_address(_isFactoryPool ? metaPoolFactoryId : registryId); address poolAddress = ICurveRegistry(poolRegistry).find_pool_for_coins(_from, _to, _index); if (poolAddress != address(0)) { _safeApproveHelper(_from, poolAddress, _dx); (int128 i, int128 j, ) = ICurveRegistry(poolRegistry).get_coin_indices(poolAddress, _from, _to); ICurveFi(poolAddress).exchange(i, j, _dx, 0); } } function _add_liquidity_single_coin( address swap, address pool, address inputToken, uint256 inputAmount, uint256 inputPosition, uint256 numPoolElements, uint256 min_mint_amount ) internal { _safeApproveHelper(inputToken, swap, inputAmount); if (numPoolElements == 2) { uint256[2] memory convertedAmounts; convertedAmounts[inputPosition] = inputAmount; ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount); } else if (numPoolElements == 3) { uint256[3] memory convertedAmounts; convertedAmounts[inputPosition] = inputAmount; ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount); } else if (numPoolElements == 4) { uint256[4] memory convertedAmounts; convertedAmounts[inputPosition] = inputAmount; ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount); } else { revert("Invalid number of amount elements"); } } function _add_liquidity( address pool, uint256[2] memory amounts, uint256 min_mint_amount ) internal { ICurveFi(pool).add_liquidity(amounts, min_mint_amount); } function _add_liquidity( address pool, uint256[3] memory amounts, uint256 min_mint_amount ) internal { ICurveFi(pool).add_liquidity(amounts, min_mint_amount); } function _add_liquidity( address pool, uint256[4] memory amounts, uint256 min_mint_amount ) internal { ICurveFi(pool).add_liquidity(amounts, min_mint_amount); } function _remove_liquidity_one_coin( address swap, uint256 _token_amount, int128 i, uint256 _min_amount ) internal { ICurveFi(swap).remove_liquidity_one_coin(_token_amount, i, _min_amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "deps/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./BaseSwapper.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/uniswap/IUniswapV2Factory.sol"; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract UniswapSwapper is BaseSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address internal constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap router address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router function _swapExactTokensForTokens( address router, address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, router, balance); IUniswapRouterV2(router).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapExactETHForTokens( address router, uint256 balance, address[] memory path ) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapExactTokensForETH( address router, address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, router, balance); IUniswapRouterV2(router).swapExactTokensForETH(balance, 0, path, address(this), now); } function _getPair( address router, address token0, address token1 ) internal view returns (address) { address factory = IUniswapRouterV2(router).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _addMaxLiquidity( address router, address token0, address token1 ) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, router, _token0Balance); _safeApproveHelper(token1, router, _token1Balance); IUniswapRouterV2(router).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } function _addMaxLiquidityEth(address router, address token0) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _ethBalance = address(this).balance; _safeApproveHelper(token0, router, _token0Balance); IUniswapRouterV2(router).addLiquidityETH{value: address(this).balance}(token0, _token0Balance, 0, 0, address(this), block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "interfaces/curve/ICurveFi.sol"; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract TokenSwapPathRegistry { mapping(address => mapping(address => address[])) public tokenSwapPaths; event TokenSwapPathSet(address tokenIn, address tokenOut, address[] path); function getTokenSwapPath(address tokenIn, address tokenOut) public view returns (address[] memory) { return tokenSwapPaths[tokenIn][tokenOut]; } function _setTokenSwapPath( address tokenIn, address tokenOut, address[] memory path ) internal { tokenSwapPaths[tokenIn][tokenOut] = path; emit TokenSwapPathSet(tokenIn, tokenOut, path); } } // 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); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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 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.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "../../deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/badger/IController.sol"; import "interfaces/badger/IStrategy.sol"; import "../SettAccessControl.sol"; /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController"); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual view returns (bool) { return false; } function isProtectedToken(address token) public view returns (bool) { address[] memory protectedTokens = getProtectedTokens(); for (uint256 i = 0; i < protectedTokens.length; i++) { if (token == protectedTokens[i]) { return true; } } return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee"); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee"); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee"); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold"); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() public virtual view returns (address[] memory) { return new address[](0); } /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface ICurveFi { function get_virtual_price() external view returns (uint256 out); function add_liquidity( // renbtc/tbtc pool uint256[2] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function get_dy( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external returns (uint256 out); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function remove_liquidity( uint256 _amount, uint256 deadline, uint256[2] calldata min_amounts ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 deadline) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external; function commit_new_parameters( int128 amplification, int128 new_fee, int128 new_admin_fee ) external; function apply_new_parameters() external; function revert_new_parameters() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function withdraw_admin_fees() external; function coins(int128 arg0) external returns (address out); function underlying_coins(int128 arg0) external returns (address out); function balances(int128 arg0) external returns (uint256 out); function A() external returns (int128 out); function fee() external returns (int128 out); function admin_fee() external returns (int128 out); function owner() external returns (address out); function admin_actions_deadline() external returns (uint256 out); function transfer_ownership_deadline() external returns (uint256 out); function future_A() external returns (int128 out); function future_fee() external returns (int128 out); function future_admin_fee() external returns (int128 out); function future_owner() external returns (address out); function calc_withdraw_one_coin(uint256 _token_amount, int128 _i) external view returns (uint256 out); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface ICurveExchange { function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function get_dy( int128, int128 j, uint256 dx ) external view returns (uint256); function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256 amount); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata min_amounts) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity_one_coin( uint256 _token_amounts, int128 i, uint256 min_amount ) external; } interface ICurveRegistryAddressProvider { function get_address(uint256 id) external returns (address); } interface ICurveRegistryExchange { function get_best_rate( address from, address to, uint256 amount ) external view returns (address, uint256); function exchange( address pool, address from, address to, uint256 amount, uint256 expected, address receiver ) external payable returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface ICurveRegistry { function find_pool_for_coins( address _from, address _to, uint256 _index ) external returns (address); function get_coin_indices( address _pool, address _from, address _to ) external returns ( int128, int128, bool ); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ contract BaseSwapper { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; }
SPDX-License-Identifier: MIT/
abstract contract BaseStrategyMultiSwapper is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; function _swap_uniswap( address startToken, uint256 balance, address[] memory path function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); function depositAll(uint256 _pid, bool _stake) external returns (bool); function withdraw(uint256 _pid, uint256 _amount) external returns (bool); function withdrawAll(uint256 _pid) external returns (bool); } pragma solidity >=0.6.0; } pragma solidity ^0.6.0; } pragma solidity ^0.6.0; } pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/uniswap/IUniswapV2Factory.sol"; import "interfaces/badger/IController.sol"; import "interfaces/badger/IStrategy.sol"; import "../SettAccessControl.sol"; import "./BaseStrategy.sol"; Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _swap_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn_uniswap(uint256 balance, address[] memory path) internal { } IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); function _swapEthIn_sushiswap(uint256 balance, address[] memory path) internal { } IUniswapRouterV2(sushiswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); function _swapEthOut_uniswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _swapEthOut_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _get_uni_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(uniswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } function _get_sushi_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(sushiswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn(uint256 balance, address[] memory path) internal { } IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } function _add_max_liquidity_sushiswap(address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, sushiswap, _token0Balance); _safeApproveHelper(token1, sushiswap, _token1Balance); IUniswapRouterV2(sushiswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } function _add_max_liquidity_eth_sushiswap(address token0) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _ethBalance = address(this).balance; _safeApproveHelper(token0, sushiswap, _token0Balance); } uint256[50] private __gap; IUniswapRouterV2(sushiswap).addLiquidityETH{value: address(this).balance}(token0, _token0Balance, 0, 0, address(this), block.timestamp); }
10,328,010
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 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, 17801, 6835, 3360, 4525, 5002, 12521, 457, 353, 3360, 4525, 288, 203, 565, 1450, 14060, 654, 39, 3462, 10784, 429, 364, 467, 654, 39, 3462, 10784, 429, 31, 203, 565, 1450, 5267, 10784, 429, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 203, 203, 565, 445, 389, 22270, 67, 318, 291, 91, 438, 12, 203, 3639, 1758, 787, 1345, 16, 203, 3639, 2254, 5034, 11013, 16, 203, 3639, 1758, 8526, 3778, 589, 203, 565, 445, 2845, 966, 12, 11890, 5034, 389, 6610, 13, 3903, 1476, 1135, 261, 2864, 966, 3778, 1769, 203, 203, 565, 445, 443, 1724, 12, 203, 3639, 2254, 5034, 389, 6610, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1426, 389, 334, 911, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 443, 1724, 1595, 12, 11890, 5034, 389, 6610, 16, 1426, 389, 334, 911, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 598, 9446, 1595, 12, 11890, 5034, 389, 6610, 13, 3903, 1135, 261, 6430, 1769, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 20, 31, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 203, 97, 203, 203, 203, 683, 9454, 2 ]
pragma solidity >=0.5.0; import "./Ownable.sol"; contract Lennon is Ownable { event newPreQuestion(uint prequestion_id, string question, string subtitle, string picture_ipfs, uint time, uint owner_id); event signed(uint prequestion_id, uint owner_id); event newQuestion(uint question_id, string question, string subtitle, string picture_ipfs, uint time, uint owner_id); event newAccount(uint id, string name, uint birth_day, uint birth_month, uint birth_year); event newReply(uint question_id, uint reply_id, string reply, bool endorse, uint time, uint owner_id); event liked(uint question_id, uint reply_id, uint owner_id); event modifyAccount(uint id, string new_name); struct Account { string name; uint8 birth_day; uint8 birth_month; uint16 birth_year; } struct Reply { string reply; bool endorse; uint time; uint owner_id; uint[] likes; } struct Question { string question; string subtitle; string picture_ipfs; uint time; uint owner_id; uint[] replies; } struct PreQuestion { string question; string subtitle; string picture_ipfs; uint time; uint owner_id; uint[] petitions; } Account[] public Accounts; mapping (address => uint) owner_to_id; PreQuestion[] public PreQuestions; Question[] public Questions; Reply[] public Replies; uint petition_threshold; modifier needAccount() { require(owner_to_id[msg.sender] != 0, "Must create an account first"); _; } constructor() public { Accounts.push(Account("admin", 0, 0, 0)); petition_threshold = 3; Questions.push(Question("你支持反送中嗎?", "暴政,暴民?","QmbFwywTUQ5NPxeW2KwftL59FQ7UQFRuw31EYqFUWpBNot", 0, 0, new uint[](0))); Questions.push(Question("你滿意大選結果嗎?", "2020大選","QmSqBScM7EnyFhkmmGb5hGVYnSfC2eaNUqUCwAHi7QRrZN", 1, 0, new uint[](0))); Questions.push(Question("你支持以核養綠嗎?", "嗨", "QmbFwywTUQ5NPxeW2KwftL59FQ7UQFRuw31EYqFUWpBNot",3, 0, new uint[](0))); } // modify petition_threshold (only owner of the contract) function modify_petition_threshold(uint _t) public onlyOwner { petition_threshold = _t; } // create an account given name and birthday function create_account(string memory _name, uint8 _d, uint8 _m, uint16 _y) public { require(owner_to_id[msg.sender] == 0, "Cannot create more than one account"); uint id = Accounts.push(Account(_name, _d, _m, _y)) - 1; owner_to_id[msg.sender] = id; emit newAccount(id, _name, _d, _m, _y); } function modify_account_info(string memory _new_name) public needAccount { Accounts[owner_to_id[msg.sender]].name = _new_name; emit modifyAccount(owner_to_id[msg.sender], _new_name); } // create a preQuestion waiting for petitions function create_prequestion(string memory _p, string memory _s, string memory _pic, uint _t) public needAccount { PreQuestions.push(PreQuestion(_p, _s, _pic, _t, owner_to_id[msg.sender], new uint[](0))); uint p_id = PreQuestions[PreQuestions.length-1].petitions.push(owner_to_id[msg.sender]); emit newPreQuestion(p_id, _p, _s, _pic, _t, owner_to_id[msg.sender]); } // sign a preQuestion function sign(uint _p_id) public needAccount { bool b = false; for(uint i = 0; i < PreQuestions[_p_id].petitions.length; i++){ if(owner_to_id[msg.sender] == PreQuestions[_p_id].petitions[i]){ b = true; break; } } require(!b, "Can only sign once"); PreQuestions[_p_id].petitions.push(owner_to_id[msg.sender]); emit signed(_p_id, owner_to_id[msg.sender]); } // turn the _p_id(th) prequestion into question function create_question(uint _p_id, uint _t) public needAccount { PreQuestion memory p = PreQuestions[_p_id]; require(owner_to_id[msg.sender] == p.owner_id, "Can only turn oneself's prequestion into a question"); require(p.petitions.length >= petition_threshold, "Not enough people signed the question"); uint id = Questions.push(Question(p.question, p.subtitle, p.picture_ipfs, _t, p.owner_id, new uint[](0))); PreQuestions[_p_id] = PreQuestions[PreQuestions.length-1]; PreQuestions.length--; emit newQuestion(id, p.question, p.subtitle, p.picture_ipfs, _t, p.owner_id); } // create a reply of a question function create_reply(uint8 _q_id, string memory _reply, bool _endorse, uint _time) public needAccount { uint owner_id = owner_to_id[msg.sender]; uint r_id = Replies.push(Reply(_reply, _endorse, _time, owner_id, new uint[](0))) - 1; Questions[_q_id].replies.push(r_id); emit newReply(_q_id, r_id, _reply, _endorse, _time, owner_id); } // like a reply (_r_idx(th) reply of the question) function like(uint8 _q_id, uint8 _r_idx) public needAccount { bool b = false; Reply storage r = Replies[Questions[_q_id].replies[_r_idx]]; for(uint i = 0; i < r.likes.length; i++) { if(r.likes[i] == owner_to_id[msg.sender]) { b = true; break; } } require(!b, "Already liked"); r.likes.push(owner_to_id[msg.sender]); emit liked(_q_id, _r_idx, owner_to_id[msg.sender]); } // get name and birthday of the user function get_account() external view needAccount returns(uint, string memory, uint8, uint8, uint16) { Account memory a = Accounts[owner_to_id[msg.sender]]; return (owner_to_id[msg.sender], a.name, a.birth_day, a.birth_month, a.birth_year); } // get name and birthday of the user given id function get_account(uint _id) external view returns(string memory, uint8, uint8, uint16) { require(_id != 0, "id should not be 0"); Account memory a = Accounts[_id]; return (a.name, a.birth_day, a.birth_month, a.birth_year); } // get total number of prequestions function get_prequestion_length() external view returns(uint) { return PreQuestions.length; } // get prequestion given prequestionId (question, subtitle, picture_ipfs, create_time, owner_id, # sign, and whether the account had signed) function get_prequestion(uint _p_id) external view returns(string memory, string memory, string memory, uint, uint, uint, bool) { PreQuestion memory p = PreQuestions[_p_id]; bool b = false; if(owner_to_id[msg.sender] != 0){ for(uint i = 0; i < p.petitions.length; i++){ if(owner_to_id[msg.sender] == p.petitions[i]){ b = true; break; } } } return (p.question, p.subtitle, p.picture_ipfs, p.time, p.owner_id, p.petitions.length, b); } // get petition threshold for changing a question into a prequestion function get_petition_threshold() external view returns(uint) { return petition_threshold; } // get total number of questions function get_question_length() external view returns(uint) { return Questions.length; } // get question given questionId (question, subtitle, picture_ipfs, last_update_time, owner_id) function get_question(uint _q_id) external view returns(string memory, string memory, string memory, uint, uint) { Question memory q = Questions[_q_id]; if( q.replies.length == 0 ) return (q.question, q.subtitle, q.picture_ipfs, q.time, q.owner_id); return (q.question, q.subtitle, q.picture_ipfs, Replies[q.replies[q.replies.length - 1]].time, q.owner_id); } // get total number of replies to a question function get_reply_length(uint _q_id) external view returns(uint) { return Questions[_q_id].replies.length; } // get _r_idx(th) reply to _q_id(th) question (reply, endorse, time, owner_id, #likes, and whether the account liked it) function get_reply(uint _q_id, uint _r_idx ) external view returns(string memory, bool ,uint ,uint ,uint, bool) { Reply memory r = Replies[Questions[_q_id].replies[_r_idx]]; bool b = false; if( owner_to_id[msg.sender] != 0 ){ for(uint i = 0; i < r.likes.length; i++) { if(r.likes[i] == owner_to_id[msg.sender]) { b = true; break; } } } return (r.reply, r.endorse, r.time, r.owner_id, r.likes.length, b); } // get all question of an account /* Usage: For the first time call get get_all_questions(-1) and get x, the first question. Then call get_all_questions(x) to get the next question iteratively until -1 returned. */ function get_all_questions(int _q_id) external view needAccount returns(int) { for(uint i = uint(_q_id + 1); i < Questions.length; i++){ if(Questions[i].owner_id == owner_to_id[msg.sender]) return int(i); } return -1; } // get all prequestion of an account /* Usage: For the first time call get get_all_prequestions(-1) and get x, the first prequestion. Then call get_all_prequestions(x) to get the next prequestion iteratively until -1 returned. */ function get_all_prequestions(int _p_id) external view needAccount returns(int) { for(uint i = uint(_p_id + 1); i < PreQuestions.length; i++){ if(PreQuestions[i].owner_id == owner_to_id[msg.sender]) return int(i); } return -1; } // get all replies of an account iteratively (_r_idx(th) reply to the question with id = _q_id) /* Usage: For the first time call get_all_replies(-1,-1) and get (x, y), the first reply. Then call get_all_replies(x, y) to get the next reply iteratively until (-1, -1) returned. */ function get_all_replies(int _q_id, int _r_idx) external view needAccount returns(int, int) { uint i = uint(_q_id == -1? 0 : _q_id); uint j = uint(_r_idx + 1); for(; i < Questions.length; i++){ for(; j < Questions[i].replies.length; j++){ if(Replies[Questions[i].replies[j]].owner_id == owner_to_id[msg.sender]) return (int(i), int(j)); } j = 0; } return (-1, -1); } }
create a preQuestion waiting for petitions
function create_prequestion(string memory _p, string memory _s, string memory _pic, uint _t) public needAccount { PreQuestions.push(PreQuestion(_p, _s, _pic, _t, owner_to_id[msg.sender], new uint[](0))); uint p_id = PreQuestions[PreQuestions.length-1].petitions.push(owner_to_id[msg.sender]); emit newPreQuestion(p_id, _p, _s, _pic, _t, owner_to_id[msg.sender]); }
12,701,085
[ 1, 2640, 279, 675, 11665, 7336, 364, 293, 278, 5029, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 67, 1484, 4173, 12, 1080, 3778, 389, 84, 16, 533, 3778, 389, 87, 16, 533, 3778, 389, 20003, 16, 2254, 389, 88, 13, 1071, 1608, 3032, 288, 203, 3639, 2962, 30791, 1115, 18, 6206, 12, 1386, 11665, 24899, 84, 16, 389, 87, 16, 389, 20003, 16, 389, 88, 16, 3410, 67, 869, 67, 350, 63, 3576, 18, 15330, 6487, 394, 2254, 8526, 12, 20, 3719, 1769, 203, 3639, 2254, 293, 67, 350, 273, 2962, 30791, 1115, 63, 1386, 30791, 1115, 18, 2469, 17, 21, 8009, 6951, 5029, 18, 6206, 12, 8443, 67, 869, 67, 350, 63, 3576, 18, 15330, 19226, 203, 3639, 3626, 394, 1386, 11665, 12, 84, 67, 350, 16, 389, 84, 16, 389, 87, 16, 389, 20003, 16, 389, 88, 16, 3410, 67, 869, 67, 350, 63, 3576, 18, 15330, 19226, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/Strings.sol'; import './CAIC.sol'; import './Randomize.sol'; import "./IBMP.sol"; /// @title CaicGrids /// @author tfs128 (@trickerfs128) contract CaicGrids is CAIC { using Strings for uint256; using Strings for uint32; using Randomize for Randomize.Random; IBMP public immutable _bmp; /// @notice constructor /// @param contractURI can be empty /// @param openseaProxyRegistry can be address zero /// @param bmp encoder address constructor( string memory contractURI, address openseaProxyRegistry, address bmp ) CAIC(contractURI, openseaProxyRegistry) { _bmp = IBMP(bmp); } /// @dev Rendering function; should be overrode /// @param tokenId the tokenId /// @param seed the seed /// @param isSvg true=svg, false=base64 encoded function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' height='",sizeInString,"' width='",sizeInString,"'>" "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', '"properties":{ "Rule":"',rule.toString(),'"},', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } /// @notice Gas eater function, to generate cells on grid /// @param rule CA rule 1-255 /// @param random to generate random initial row. function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } uint8 increment; if(SIZE <= 256) { increment = 3; } else if(SIZE <= 384) { increment = 2; } else { increment = 1; } for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += increment; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } } // 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 './BaseOpenSea.sol'; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /// @title CAIC (Cellular Automaton In Chain) /// @author Tfs128 (@trickerfs128) /// @dev most of the code borrowed from [sol]Seedlings contract written by Simon Fremaux (@dievardump) contract CAIC is BaseOpenSea, ERC721Enumerable,Ownable,ReentrancyGuard { event SeedChangeRequest(uint256 indexed tokenId, address indexed operator); event Collected(address indexed operator, uint256 indexed count,uint256 value); event Claimed(address indexed operator); event SizeUpdated(uint32 size); // Last Token Id Generated. uint256 public LAST_TOKEN_ID; //public minting start time. uint256 public PUBLIC_MINTING_TIME = block.timestamp + 36 hours; // 0.00768 uint256 public PRICE = 7680000000000000; // Max Available for mint `Available` - `Reserved` uint256 public AVAILABLE = 509; // 257 reserved for blockglyphs holders + 2 for owner uint256 public BG_RESERVED_LEFT = 259; // Max mints allowed in single transaction uint256 public MAX_MINT = 11; // Last Seed Generated bytes32 public LAST_SEED; // Size of image height:=SIZE, width:=SIZE uint32 public SIZE = 256; // each token seed mapping(uint256 => bytes32) internal _tokenSeed; // tokenIds with a request for seeds change mapping(uint256 => bool) private _seedChangeRequests; // blockGlyph holders mapping(address => bool) public _bgHolders; /// @notice constructor /// @param contractURI can be empty /// @param openseaProxyRegistry can be address zero constructor( string memory contractURI, address openseaProxyRegistry ) ERC721('CAIC', 'CAIC') { //CAIC (Cellular Automaton In Chain) if (bytes(contractURI).length > 0) { _setContractURI(contractURI); } if (address(0) != openseaProxyRegistry) { _setOpenSeaRegistry(openseaProxyRegistry); } } /// @notice function to mint `count` token(s) to `msg.sender` /// @param count numbers of tokens function mint(uint256 count) external payable nonReentrant { require (block.timestamp >= PUBLIC_MINTING_TIME, 'Wait'); require(count > 0, 'Must be greater than 0'); require(count <= MAX_MINT, 'More Than Max Allowed.' ); require(count <= AVAILABLE, 'Too Many Requested.'); require(msg.value == PRICE * count , 'Not Enough Amount.'); uint256 tokenId = LAST_TOKEN_ID; bytes32 blockHash = blockhash(block.number - 1); bytes32 nextSeed; for (uint256 i; i < count; i++) { tokenId++; _safeMint(msg.sender, tokenId); nextSeed = keccak256( abi.encodePacked( LAST_SEED, block.timestamp, msg.sender, blockHash, block.coinbase, block.difficulty, tx.gasprice ) ); LAST_SEED = nextSeed; _tokenSeed[tokenId] = nextSeed; } LAST_TOKEN_ID = tokenId; AVAILABLE -= count; emit Collected(msg.sender, count, msg.value); } /// @notice func for free token claim for blockglyph holders function claim() external { require (block.timestamp < PUBLIC_MINTING_TIME, 'You are late.'); //I had made a blunder in previouse deployment, so had to redeploy again. //rather than storing whole reserve list again, will use it from //previouse contract. require (CAIC(0xb742848B5971cE5D0628E351714AF5F1F4e4A8A2)._bgHolders(msg.sender) == true, 'Not a bg holder.'); require (_bgHolders[msg.sender] == false , 'Already claimed.'); uint256 tokenId = LAST_TOKEN_ID + 1; _safeMint(msg.sender, tokenId); bytes32 blockHash = blockhash(block.number - 1); bytes32 nextSeed = keccak256( abi.encodePacked( LAST_SEED, block.timestamp, msg.sender, blockHash, block.coinbase, block.difficulty, tx.gasprice ) ); LAST_TOKEN_ID = tokenId; LAST_SEED = nextSeed; _tokenSeed[tokenId] = nextSeed; BG_RESERVED_LEFT -= 1; _bgHolders[msg.sender] = true; emit Claimed(msg.sender); } /// @notice function to request seed change by token owner. /// @param tokenId of which seed change requested function requestSeedChange(uint256 tokenId) external { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); _seedChangeRequests[tokenId] = true; emit SeedChangeRequest(tokenId, msg.sender); } /// opensea config (https://docs.opensea.io/docs/contract-level-metadata) function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } ///@notice function to update image res ///@param imageSize height X width = 'imageSize * imageSize' function updateImageSize(uint32 imageSize) external onlyOwner { require(imageSize % 4 == 0, 'Should be a multiple of 4'); require(imageSize > 63 && imageSize < 513, 'Must be between 64-512'); SIZE = imageSize; emit SizeUpdated(imageSize); } /// @dev blockglyphs holders struct. struct bgHolderAddresses { address addr; bool available; } /// @notice function to add blockglyph holders + 2 owner reserved function addBgHolders(bgHolderAddresses[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _bgHolders[addresses[i].addr] = addresses[i].available; } } ///@notice function to respond to seed change requests ///@param tokenId of which seed needs to be change function changeSeedAfterRequest(uint256 tokenId) external onlyOwner { require(_seedChangeRequests[tokenId] == true, 'No request for token.'); _seedChangeRequests[tokenId] = false; _tokenSeed[tokenId] = keccak256( abi.encode( _tokenSeed[tokenId], block.timestamp, block.difficulty, blockhash(block.number - 1) ) ); } /// @notice function to withdraw balance. function withdraw() external onlyOwner { require(address(this).balance > 0, "0 Balance."); bool success; (success, ) = msg.sender.call{value: address(this).balance}(''); require(success, 'Failed'); } /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32) { require(_exists(tokenId), 'TokenSeed query for nonexistent token'); return _tokenSeed[tokenId]; } /// @notice function to get raw based64 encoded image /// @param tokenId id of token function getRaw(uint256 tokenId) public view returns (string memory) { require( _exists(tokenId), 'Query for nonexistent token' ); return _render(tokenId, _tokenSeed[tokenId],false); } /// @notice tokenURI override that returns a data:json application /// @inheritdoc ERC721 function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); return _render(tokenId, _tokenSeed[tokenId],true); } /// @notice Called with the sale price to determine how much royalty /// @param tokenId - the NFT asset queried for royalty information /// @param value - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 tokenId, uint256 value) public view returns (address receiver, uint256 royaltyAmount) { receiver = owner(); royaltyAmount = (value * 300) / 10000; } /// @notice Function allowing to check the rendering for a given seed /// @param seed the seed to render function renderSeed(bytes32 seed) public view returns (string memory) { return _render(1, seed, false); } /// @dev Rendering function; /// @param tokenId which needs to be render /// @param seed seed which needs to be render /// @param isSvg true=svg, false=base64 encoded function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view virtual returns (string memory) { seed; return string( abi.encodePacked( 'data:application/json,{"name":"', tokenId, '"}' ) ); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // small library to randomize using (min, max, seed, offsetBit etc...) library Randomize { struct Random { uint256 seed; uint256 offsetBit; } /// @notice get an random number between (min and max) using seed and offseting bits /// this function assumes that max is never bigger than 0xffffff (hex color with opacity included) /// @dev this function is simply used to get random number using a seed. /// if does bitshifting operations to try to reuse the same seed as much as possible. /// should be enough for anyth /// @param random the randomizer /// @param min the minimum /// @param max the maximum /// @return result the resulting pseudo random number function next( Random memory random, uint256 min, uint256 max ) internal pure returns (uint256 result) { uint256 newSeed = random.seed; uint256 newOffset = random.offsetBit + 3; uint256 maxOffset = 4; uint256 mask = 0xf; if (max > 0xfffff) { mask = 0xffffff; maxOffset = 24; } else if (max > 0xffff) { mask = 0xfffff; maxOffset = 20; } else if (max > 0xfff) { mask = 0xffff; maxOffset = 16; } else if (max > 0xff) { mask = 0xfff; maxOffset = 12; } else if (max > 0xf) { mask = 0xff; maxOffset = 8; } // if offsetBit is too high to get the max number // just get new seed and restart offset to 0 if (newOffset > (256 - maxOffset)) { newOffset = 0; newSeed = uint256(keccak256(abi.encode(newSeed))); } uint256 offseted = (newSeed >> newOffset); uint256 part = offseted & mask; result = min + (part % (max - min)); random.seed = newSeed; random.offsetBit = newOffset; } function nextInt( Random memory random, uint256 min, uint256 max ) internal pure returns (int256 result) { result = int256(Randomize.next(random, min, max)); } } // SPDX-License-Identifier: MIT // Copyright 2021 Arran Schlosberg / Twitter @divergence_art pragma solidity >=0.8.0 <0.9.0; /// @title IBMP interface /// @dev interface of BMP.sol originally used in brotchain (0xd31fc221d2b0e0321c43e9f6824b26ebfff01d7d) interface IBMP { /// @notice Returns an 8-bit grayscale palette for bitmap images. function grayscale() external pure returns (bytes memory); /// @notice Returns an 8-bit BMP encoding of the pixels. /// @param pixels bytes array of pixels /// @param width - /// @param height - /// @param palette bytes array function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) external pure returns (bytes memory); /// @notice Returns the buffer, presumably from bmp(), as a base64 data URI. /// @param bmpBuf encoded bytes of pixels function bmpDataURI(bytes memory bmpBuf) external pure returns (string memory); /// @notice Scale pixels by repetition along both axes. /// @param pixels bytes array of pixels /// @param width - /// @param height - /// @param scale - function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) external pure returns (bytes memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's support contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry) != address(0) && // current operator is owner's proxy address address(proxyRegistry.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 () { 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.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.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}. 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 || 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 _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // 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` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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 that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
@notice func for free token claim for blockglyph holdersI had made a blunder in previouse deployment, so had to redeploy again.rather than storing whole reserve list again, will use it frompreviouse contract.
function claim() external { require (block.timestamp < PUBLIC_MINTING_TIME, 'You are late.'); require (CAIC(0xb742848B5971cE5D0628E351714AF5F1F4e4A8A2)._bgHolders(msg.sender) == true, 'Not a bg holder.'); require (_bgHolders[msg.sender] == false , 'Already claimed.'); uint256 tokenId = LAST_TOKEN_ID + 1; _safeMint(msg.sender, tokenId); bytes32 blockHash = blockhash(block.number - 1); bytes32 nextSeed = keccak256( abi.encodePacked( LAST_SEED, block.timestamp, msg.sender, blockHash, block.coinbase, block.difficulty, tx.gasprice ) ); LAST_TOKEN_ID = tokenId; LAST_SEED = nextSeed; _tokenSeed[tokenId] = nextSeed; BG_RESERVED_LEFT -= 1; _bgHolders[msg.sender] = true; emit Claimed(msg.sender); }
13,390,728
[ 1, 644, 364, 4843, 1147, 7516, 364, 1203, 19426, 366, 4665, 45, 9323, 7165, 279, 2811, 9341, 316, 675, 522, 3793, 6314, 16, 1427, 9323, 358, 283, 12411, 3382, 18, 86, 4806, 2353, 15729, 7339, 20501, 666, 3382, 16, 903, 999, 518, 628, 1484, 522, 3793, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 7516, 1435, 3903, 288, 203, 3639, 2583, 261, 2629, 18, 5508, 411, 17187, 67, 49, 3217, 1360, 67, 4684, 16, 296, 6225, 854, 26374, 1093, 1769, 203, 3639, 2583, 261, 3587, 2871, 12, 20, 6114, 5608, 22, 5193, 28, 38, 6162, 11212, 71, 41, 25, 40, 7677, 6030, 41, 4763, 4033, 3461, 6799, 25, 42, 21, 42, 24, 73, 24, 37, 28, 37, 22, 2934, 67, 12370, 27003, 12, 3576, 18, 15330, 13, 422, 638, 16, 296, 1248, 279, 7611, 10438, 1093, 1769, 203, 3639, 2583, 261, 67, 12370, 27003, 63, 3576, 18, 15330, 65, 422, 629, 269, 296, 9430, 7516, 329, 1093, 1769, 203, 3639, 2254, 5034, 1147, 548, 273, 15612, 67, 8412, 67, 734, 397, 404, 31, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 1147, 548, 1769, 203, 3639, 1731, 1578, 31493, 273, 1203, 2816, 12, 2629, 18, 2696, 300, 404, 1769, 203, 3639, 1731, 1578, 1024, 12702, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 15612, 67, 1090, 2056, 16, 203, 7734, 1203, 18, 5508, 16, 203, 7734, 1234, 18, 15330, 16, 203, 7734, 31493, 16, 203, 7734, 1203, 18, 12645, 1969, 16, 203, 7734, 1203, 18, 5413, 21934, 16, 203, 7734, 2229, 18, 31604, 8694, 203, 7734, 262, 203, 5411, 11272, 203, 3639, 15612, 67, 8412, 67, 734, 273, 1147, 548, 31, 203, 3639, 15612, 67, 1090, 2056, 273, 1024, 12702, 31, 203, 3639, 389, 2316, 12702, 63, 2316, 548, 65, 273, 1024, 12702, 31, 203, 2 ]
pragma solidity ^0.4.10; /** * @title Interface to communicate with ICO token contract */ contract IToken { function balanceOf(address _address) constant returns (uint balance); function transferFromOwner(address _to, uint256 _value) returns (bool success); } /** * @title Presale token contract */ contract TokenEscrow { // Token-related properties/description to display in Wallet client / UI string public standard = 'PBKXToken 0.3'; string public name = 'PBKXToken'; string public symbol = 'PBKX'; uint public decimals = 2; uint public totalSupply = 300000000; IToken icoToken; event Converted(address indexed from, uint256 value); // Event to inform about the fact of token burning/destroying event Transfer(address indexed from, address indexed to, uint256 value); event Error(bytes32 error); mapping (address => uint) balanceFor; // Presale token balance for each of holders address owner; // Contract owner uint public exchangeRate; // preICO -> ICO token exchange rate // Token supply and discount policy structure struct TokenSupply { uint limit; // Total amount of tokens uint totalSupply; // Current amount of sold tokens uint tokenPriceInWei; // Number of token per 1 Eth } TokenSupply[3] public tokenSupplies; // Modifiers modifier owneronly { if (msg.sender == owner) _; } /** * @dev Set/change contract owner * @param _owner owner address */ function setOwner(address _owner) owneronly { owner = _owner; } function setRate(uint _exchangeRate) owneronly { exchangeRate = _exchangeRate; } function setToken(address _icoToken) owneronly { icoToken = IToken(_icoToken); } /** * @dev Returns balance/token quanity owned by address * @param _address Account address to get balance for * @return balance value / token quantity */ function balanceOf(address _address) constant returns (uint balance) { return balanceFor[_address]; } /** * @dev Transfers tokens from caller/method invoker/message sender to specified recipient * @param _to Recipient address * @param _value Token quantity to transfer * @return success/failure of transfer */ function transfer(address _to, uint _value) returns (bool success) { if(_to != owner) { if (balanceFor[msg.sender] < _value) return false; // Check if the sender has enough if (balanceFor[_to] + _value < balanceFor[_to]) return false; // Check for overflows if (msg.sender == owner) { transferByOwner(_value); } balanceFor[msg.sender] -= _value; // Subtract from the sender balanceFor[_to] += _value; // Add the same to the recipient Transfer(owner,_to,_value); return true; } return false; } function transferByOwner(uint _value) private { for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) { TokenSupply storage tokenSupply = tokenSupplies[discountIndex]; if(tokenSupply.totalSupply < tokenSupply.limit) { if (tokenSupply.totalSupply + _value > tokenSupply.limit) { _value -= tokenSupply.limit - tokenSupply.totalSupply; tokenSupply.totalSupply = tokenSupply.limit; } else { tokenSupply.totalSupply += _value; break; } } } } /** * @dev Burns/destroys specified amount of Presale tokens for caller/method invoker/message sender * @return success/failure of transfer */ function convert() returns (bool success) { if (balanceFor[msg.sender] == 0) return false; // Check if the sender has enough if (!exchangeToIco(msg.sender)) return false; // Try to exchange preICO tokens to ICO tokens Converted(msg.sender, balanceFor[msg.sender]); balanceFor[msg.sender] = 0; // Subtract from the sender return true; } /** * @dev Converts/exchanges sold Presale tokens to ICO ones according to provided exchange rate * @param owner address */ function exchangeToIco(address owner) private returns (bool) { if(icoToken != address(0)) { return icoToken.transferFromOwner(owner, balanceFor[owner] * exchangeRate); } return false; } /** * @dev Presale contract constructor */ function TokenEscrow() { owner = msg.sender; balanceFor[msg.sender] = 300000000; // Give the creator all initial tokens // Discount policy tokenSupplies[0] = TokenSupply(100000000, 0, 11428571428571); // First million of tokens will go 11210762331838 wei for 1 token tokenSupplies[1] = TokenSupply(100000000, 0, 11848341232227); // Second million of tokens will go 12106537530266 wei for 1 token tokenSupplies[2] = TokenSupply(100000000, 0, 12500000000000); // Third million of tokens will go 13245033112582 wei for 1 token //Balances recovery transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,875); transferByOwner(875); transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,2150); transferByOwner(2150); transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,975); transferByOwner(975); transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,875000); transferByOwner(875000); transferFromOwner(0xa4a90f8d12ae235812a4770e0da76f5bc2fdb229,3500000); transferByOwner(3500000); transferFromOwner(0xbd08c225306f6b341ce5a896392e0f428b31799c,43750); transferByOwner(43750); transferFromOwner(0xf948fc5be2d2fd8a7ee20154a18fae145afd6905,3316981); transferByOwner(3316981); transferFromOwner(0x23f15982c111362125319fd4f35ac9e1ed2de9d6,2625); transferByOwner(2625); transferFromOwner(0x23f15982c111362125319fd4f35ac9e1ed2de9d6,5250); transferByOwner(5250); transferFromOwner(0x6ebff66a68655d88733df61b8e35fbcbd670018e,58625); transferByOwner(58625); transferFromOwner(0x1aaa29dffffc8ce0f0eb42031f466dbc3c5155ce,1043875); transferByOwner(1043875); transferFromOwner(0x5d47871df00083000811a4214c38d7609e8b1121,3300000); transferByOwner(3300000); transferFromOwner(0x30ced0c61ccecdd17246840e0d0acb342b9bd2e6,261070); transferByOwner(261070); transferFromOwner(0x1079827daefe609dc7721023f811b7bb86e365a8,2051875); transferByOwner(2051875); transferFromOwner(0x6c0b6a5ac81e07f89238da658a9f0e61be6a0076,10500000); transferByOwner(10500000); transferFromOwner(0xd16e29637a29d20d9e21b146fcfc40aca47656e5,1750); transferByOwner(1750); transferFromOwner(0x4c9ba33dcbb5876e1a83d60114f42c949da4ee22,7787500); transferByOwner(7787500); transferFromOwner(0x0d8cc80efe5b136865b9788393d828fd7ffb5887,100000000); transferByOwner(100000000); } // Incoming transfer from the Presale token buyer function() payable { uint tokenAmount; // Amount of tzokens which is possible to buy for incoming transfer/payment uint amountToBePaid; // Amount to be paid uint amountTransfered = msg.value; // Cost/price in WEI of incoming transfer/payment if (amountTransfered <= 0) { Error('no eth was transfered'); msg.sender.transfer(msg.value); return; } if(balanceFor[owner] <= 0) { Error('all tokens sold'); msg.sender.transfer(msg.value); return; } // Determine amount of tokens can be bought according to available supply and discount policy for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) { // If it's not possible to buy any tokens at all skip the rest of discount policy TokenSupply storage tokenSupply = tokenSupplies[discountIndex]; if(tokenSupply.totalSupply < tokenSupply.limit) { uint tokensPossibleToBuy = amountTransfered / tokenSupply.tokenPriceInWei; if (tokensPossibleToBuy > balanceFor[owner]) tokensPossibleToBuy = balanceFor[owner]; if (tokenSupply.totalSupply + tokensPossibleToBuy > tokenSupply.limit) { tokensPossibleToBuy = tokenSupply.limit - tokenSupply.totalSupply; } tokenSupply.totalSupply += tokensPossibleToBuy; tokenAmount += tokensPossibleToBuy; uint delta = tokensPossibleToBuy * tokenSupply.tokenPriceInWei; amountToBePaid += delta; amountTransfered -= delta; } } // Do not waste gas if there is no tokens to buy if (tokenAmount == 0) { Error('no token to buy'); msg.sender.transfer(msg.value); return; } // Transfer tokens to buyer transferFromOwner(msg.sender, tokenAmount); // Transfer money to seller owner.transfer(amountToBePaid); // Refund buyer if overpaid / no tokens to sell msg.sender.transfer(msg.value - amountToBePaid); } /** * @dev Removes/deletes contract */ function kill() owneronly { suicide(msg.sender); } /** * @dev Transfers tokens from owner to specified recipient * @param _to Recipient address * @param _value Token quantity to transfer * @return success/failure of transfer */ function transferFromOwner(address _to, uint256 _value) private returns (bool success) { if (balanceFor[owner] < _value) return false; // Check if the owner has enough if (balanceFor[_to] + _value < balanceFor[_to]) return false; // Check for overflows balanceFor[owner] -= _value; // Subtract from the owner balanceFor[_to] += _value; // Add the same to the recipient Transfer(owner,_to,_value); return true; } }
Refund buyer if overpaid / no tokens to sell
msg.sender.transfer(msg.value - amountToBePaid);
13,039,020
[ 1, 21537, 27037, 309, 1879, 29434, 342, 1158, 2430, 358, 357, 80, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 3576, 18, 15330, 18, 13866, 12, 3576, 18, 1132, 300, 3844, 15360, 16507, 350, 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 ]
./full_match/1/0xd712A863766dE7e7cA13289A97997E01832A6571/sources/contracts/BaseSmartVaultDeployer.sol
Create and setup action Set oracle signers Set protocol fee withdrawer Authorize action to call and withdraw
function _setupClaimer(SmartVault smartVault, PermissionsManager manager, ClaimerActionParams memory params) internal { Claimer claimer = Claimer(params.impl); Deployer.setupBaseAction(claimer, manager, params.admin, address(smartVault)); address[] memory executors = Arrays.from(params.admin, params.managers, params.relayedActionParams.relayers); Deployer.setupActionExecutors(claimer, manager, executors, claimer.call.selector); Deployer.setupTokenThresholdAction(claimer, manager, params.admin, params.tokenThresholdActionParams); Deployer.setupRelayedAction(claimer, manager, params.admin, params.relayedActionParams); manager.authorize(claimer, Arrays.from(params.admin, address(this)), claimer.setOracleSigner.selector); claimer.setOracleSigner(params.oracleSigner, true); manager.unauthorize(claimer, address(this), claimer.setOracleSigner.selector); manager.authorize(claimer, Arrays.from(params.admin, address(this)), claimer.setProtocolFeeWithdrawer.selector); claimer.setProtocolFeeWithdrawer(params.protocolFeeWithdrawer); manager.unauthorize(claimer, address(this), claimer.setProtocolFeeWithdrawer.selector); bytes4[] memory whats = Arrays.from(smartVault.call.selector, smartVault.withdraw.selector); manager.authorize(smartVault, address(claimer), whats); }
2,973,939
[ 1, 1684, 471, 3875, 1301, 1000, 20865, 1573, 414, 1000, 1771, 14036, 598, 9446, 264, 23859, 1301, 358, 745, 471, 598, 9446, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8401, 2009, 69, 4417, 12, 23824, 12003, 13706, 12003, 16, 15684, 1318, 3301, 16, 3905, 69, 4417, 1803, 1370, 3778, 859, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 3905, 69, 4417, 927, 69, 4417, 273, 3905, 69, 4417, 12, 2010, 18, 11299, 1769, 203, 3639, 7406, 264, 18, 8401, 2171, 1803, 12, 830, 69, 4417, 16, 3301, 16, 859, 18, 3666, 16, 1758, 12, 26416, 12003, 10019, 203, 3639, 1758, 8526, 3778, 1196, 13595, 273, 5647, 18, 2080, 12, 2010, 18, 3666, 16, 859, 18, 29757, 16, 859, 18, 2878, 528, 329, 1803, 1370, 18, 2878, 3907, 1769, 203, 3639, 7406, 264, 18, 8401, 1803, 1905, 13595, 12, 830, 69, 4417, 16, 3301, 16, 1196, 13595, 16, 927, 69, 4417, 18, 1991, 18, 9663, 1769, 203, 3639, 7406, 264, 18, 8401, 1345, 7614, 1803, 12, 830, 69, 4417, 16, 3301, 16, 859, 18, 3666, 16, 859, 18, 2316, 7614, 1803, 1370, 1769, 203, 3639, 7406, 264, 18, 8401, 27186, 329, 1803, 12, 830, 69, 4417, 16, 3301, 16, 859, 18, 3666, 16, 859, 18, 2878, 528, 329, 1803, 1370, 1769, 203, 203, 3639, 3301, 18, 22488, 12, 830, 69, 4417, 16, 5647, 18, 2080, 12, 2010, 18, 3666, 16, 1758, 12, 2211, 13, 3631, 927, 69, 4417, 18, 542, 23601, 15647, 18, 9663, 1769, 203, 3639, 927, 69, 4417, 18, 542, 23601, 15647, 12, 2010, 18, 280, 16066, 15647, 16, 638, 1769, 203, 3639, 3301, 18, 318, 22488, 12, 830, 69, 4417, 16, 1758, 12, 2211, 3631, 927, 69, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './ERC721Enumerable.sol'; import './Strings.sol'; import './INiftyNafty.sol'; import './INiftyNaftyMetadata.sol'; contract NiftyNafty is ERC721Enumerable, INiftyNafty, INiftyNaftyMetadata { using Strings for uint256; uint256 private constant startIDFrom=1;// The initial token ID uint256 public constant COUNT_PRESALE = 250; uint256 public constant PUBLIC_MAX = 8999; uint256 public constant GIFT_MAX = 1000; uint256 public constant PURCHASE_LIMIT = 3; uint256 public saleMode = 0;//0-none, 1-presale, 2-public uint256 public PRICE_PRESALE = 0.05 ether; uint256 public PRICE_WHITE = 0.07 ether; uint256 public PRICE = 0.08 ether; bool public isActive = true; bool public isAllowListActive = false; string public proof; uint256 public allowListMaxMint = 3; uint256 public totalGiftSupply; uint256 public totalPublicSupply; uint256 public startDate; address[] internal _ownersList; mapping(address => bool) private _allowList; mapping(address => uint256) private _claimed; string private _contractURI = ''; string private _tokenBaseURI = ''; string private _tokenRevealedBaseURI = ''; //---------------------------------------------------------------------------------------------------------------new // Used for random index assignment mapping(uint256 => uint256) private tokenMatrix; address public addressDAO; uint256 public constant DAO_PERCENT = 55;// 1/1000 uint256 private _allBalance; uint256 private _sentDAO; bytes32 public lastOperation; address public lastOwner; bool public revealed = false; string public notRevealedUri; constructor(string memory name, string memory symbol) ERC721(name, symbol) { _ownersList.push(_msgSender()); } function updateOwnersList(address[] calldata addresses) external override onlyTwoOwners { _ownersList = addresses; } function onOwnersList(address addr) external view override returns (bool) { for(uint i = 0; i < _ownersList.length; i++) { if (_ownersList[i] == addr) { return true; } } return false; } function addToAllowList(address[] calldata addresses) external override onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); _allowList[addresses[i]] = true; _claimed[addresses[i]] > 0 ? _claimed[addresses[i]] : 0; } } function onAllowList(address addr) external view override returns (bool) { return _allowList[addr]; } function removeFromAllowList(address[] calldata addresses) external override onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); _allowList[addresses[i]] = false; } } function setPricePreSale(uint256 newPrice) external onlyOwner { PRICE_PRESALE = newPrice; } function setPriceWhite(uint256 newPrice) external onlyOwner { PRICE_WHITE = newPrice; } function setPrice(uint256 newPrice) external override onlyOwner { PRICE = newPrice; } function setStartDate(uint256 newDate) external override onlyOwner { startDate = newDate; } function claimedBy(address addr) external view override returns (uint256){ require(addr != address(0), "Can't check the null address"); return _claimed[addr]; } function purchase(uint256 numberOfTokens) external override payable { require(block.timestamp > startDate, 'Sale not started'); require(isActive, 'Contract is not active'); require(saleMode>0, 'The sale mode is not enabled'); require(numberOfTokens <= PURCHASE_LIMIT, 'Would exceed PURCHASE_LIMIT'); if (isAllowListActive) { require(_allowList[msg.sender], 'You are not on the Allow List'); } //Mechanics of price selection uint256 Price=PRICE; if (saleMode == 1) { Price=PRICE_PRESALE; } else if(_allowList[msg.sender]){ Price=PRICE_WHITE; } //optimistic set uint256 tokenCount=totalPublicSupply; _allBalance += msg.value; _claimed[msg.sender] += numberOfTokens; totalPublicSupply += numberOfTokens; //Mechanics of determining the end of the pre sale if (saleMode == 1) { require(totalPublicSupply <= COUNT_PRESALE, 'All PRESALE tokens have been minted'); if(totalPublicSupply >= COUNT_PRESALE) saleMode=0; } require(_claimed[msg.sender] <= allowListMaxMint, 'Purchase exceeds max allowed'); require(totalPublicSupply <= PUBLIC_MAX, 'Purchase would exceed PUBLIC_MAX'); require(Price * numberOfTokens <= msg.value, 'ETH amount is not sufficient'); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = nextToken(tokenCount); tokenCount+=1; _safeMint(msg.sender, tokenId); } } function gift(address[] calldata to) external override onlyTwoOwners { require(totalGiftSupply + to.length <= GIFT_MAX, 'Not enough tokens left to gift'); uint256 tokenCount=totalGiftSupply; totalGiftSupply += to.length; for(uint256 i = 0; i < to.length; i++) { uint256 tokenId = tokenCount + PUBLIC_MAX + 1 + i; _safeMint(to[i], tokenId); } } function setIsActive(bool _isActive) external override onlyOwner { isActive = _isActive; } function setIsAllowListActive(bool _isAllowListActive) external override onlyOwner { isAllowListActive = _isAllowListActive; } function setSaleMode(uint256 _Mode) external onlyOwner { saleMode = _Mode; } function setAllowListMaxMint(uint256 maxMint) external override onlyOwner { allowListMaxMint = maxMint; } function setProof(string calldata proofString) external override onlyOwner { proof = proofString; } function withdraw() external override onlyTwoOwners { require(_ownersList.length > 0, "Can't withdraw where owners list empty"); int256 balance=int256(address(this).balance)-int256(getProfitDAO()); require(balance>0, "Can't withdraw - no funds available"); uint256 part = uint256(balance) / _ownersList.length; if(part>0) { for(uint256 i = 0; i < _ownersList.length; i++) { payable(_ownersList[i]).transfer(part); } } } function setContractURI(string calldata URI) external override onlyOwner { _contractURI = URI; } function setBaseURI(string calldata URI) external override onlyOwner { _tokenBaseURI = URI; } function setRevealedBaseURI(string calldata revealedBaseURI) external override onlyOwner { _tokenRevealedBaseURI = revealedBaseURI; } function contractURI() public view override returns (string memory) { return _contractURI; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), 'Token does not exist'); if(revealed == false) { return notRevealedUri; } string memory revealedBaseURI = _tokenRevealedBaseURI; return bytes(revealedBaseURI).length > 0 ? string(abi.encodePacked(revealedBaseURI, tokenId.toString(), '.json')) : _tokenBaseURI; } function reveal() public onlyOwner { revealed = true; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } //---------------------------------------------------------------------------------------------------------------new function setDAO(address setAddress) external onlyOwner { require(setAddress != address(0), "Can't check the null address"); addressDAO = setAddress; } function withdrawDAO() external onlyTwoOwners { uint256 ProfitDAO=getProfitDAO(); require(ProfitDAO>0, "Can't withdraw - no funds available"); require(addressDAO!= address(0), "Can't withdraw - DAO not set"); (bool success,) = payable(addressDAO).call{value:ProfitDAO, gas: 100000}(""); if(success) { _sentDAO += ProfitDAO; } } function getProfitDAO() public view returns (uint256 ProfitDAO) { int256 Balance = int256(_allBalance * DAO_PERCENT/1000) - int256(_sentDAO); if(Balance>0) ProfitDAO=uint256(Balance); else ProfitDAO=0; } /// Get the next token ID /// @dev Randomly gets a new token ID and keeps track of the ones that are still available. /// @return the next token ID function nextToken(uint256 tokenCount) internal returns (uint256) { uint256 maxIndex = PUBLIC_MAX - tokenCount; uint256 random = uint256(keccak256( abi.encodePacked( msg.sender, block.coinbase, block.difficulty, block.gaslimit, block.timestamp ) )) % maxIndex; uint256 value = 0; if (tokenMatrix[random] == 0) { // If this matrix position is empty, set the value to the generated random number. value = random; } else { // Otherwise, use the previously stored number from the matrix. value = tokenMatrix[random]; } // If the last available tokenID is still unused... if (tokenMatrix[maxIndex - 1] == 0) { // ...store that ID in the current matrix position. tokenMatrix[random] = maxIndex - 1; } else { // ...otherwise copy over the stored number to the current matrix position. tokenMatrix[random] = tokenMatrix[maxIndex - 1]; } return value + startIDFrom; } //---------------------------------------------------------------------------------------------------------MultSig 2/N // MODIFIERS /** * @dev Allows to perform method by any of the owners */ modifier onlyOwner { require(isOwner(), "onlyOwner: caller is not the owner"); _; } /** * @dev Allows to perform method only after many owners call it with the same arguments */ modifier onlyTwoOwners { require(isOwner(), "onlyTwoOwners: caller is not the owner"); bytes32 operation = keccak256(msg.data); if(_ownersList.length == 1 || (lastOperation == operation && lastOwner != msg.sender)) { resetVote(); _; } else if(lastOperation != operation || lastOwner == msg.sender) { //new vote lastOperation = operation; lastOwner = msg.sender; } } /** * @dev Returns the address of the current owner */ function owner() public view virtual returns (address) { return _ownersList[0]; } /** * @dev Returns a list of owners addresses */ function owners() public view virtual returns (address [] memory) { return _ownersList; } function isOwner()internal view returns(bool) { for(uint256 i = 0; i < _ownersList.length; i++) { if(_ownersList[i]==msg.sender) { return true; } } return false; } function resetVote()internal{ lastOperation=0; lastOwner=address(0); } /** * @dev Allows owners to change their mind by cacnelling vote operations */ function cancelVote() public onlyOwner { resetVote(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; interface INiftyNafty { function updateOwnersList(address[] calldata addresses) external; function onOwnersList(address addr) external returns (bool); function addToAllowList(address[] calldata addresses) external; function onAllowList(address addr) external returns (bool); function removeFromAllowList(address[] calldata addresses) external; function claimedBy(address owner) external returns (uint256); function purchase(uint256 numberOfTokens) external payable; function gift(address[] calldata to) external; function setIsActive(bool isActive) external; function setPrice(uint256 newPrice) external; //function setMaxTotalSupply(uint256 newCount) external; function setStartDate(uint256 newDate) external; function setIsAllowListActive(bool isAllowListActive) external; function setAllowListMaxMint(uint256 maxMint) external; function setProof(string memory proofString) external; function withdraw() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INiftyNaftyMetadata { function setContractURI(string calldata URI) external; function setBaseURI(string calldata URI) external; function setRevealedBaseURI(string calldata revealedBaseURI) external; function contractURI() external view returns(string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./Strings.sol"; import "./ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Allows to perform method only after many owners call it with the same arguments/new vote
modifier onlyTwoOwners { require(isOwner(), "onlyTwoOwners: caller is not the owner"); bytes32 operation = keccak256(msg.data); if(_ownersList.length == 1 || (lastOperation == operation && lastOwner != msg.sender)) { resetVote(); _; } else if(lastOperation != operation || lastOwner == msg.sender) { lastOperation = operation; lastOwner = msg.sender; } }
14,813,826
[ 1, 19132, 358, 3073, 707, 1338, 1839, 4906, 25937, 745, 518, 598, 326, 1967, 1775, 19, 2704, 12501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1338, 11710, 5460, 414, 288, 203, 203, 3639, 2583, 12, 291, 5541, 9334, 315, 3700, 11710, 5460, 414, 30, 4894, 353, 486, 326, 3410, 8863, 203, 203, 3639, 1731, 1578, 1674, 273, 417, 24410, 581, 5034, 12, 3576, 18, 892, 1769, 203, 203, 3639, 309, 24899, 995, 414, 682, 18, 2469, 422, 404, 747, 261, 2722, 2988, 422, 1674, 597, 1142, 5541, 480, 1234, 18, 15330, 3719, 203, 3639, 288, 203, 5411, 2715, 19338, 5621, 203, 5411, 389, 31, 203, 3639, 289, 203, 3639, 469, 203, 3639, 309, 12, 2722, 2988, 480, 1674, 747, 1142, 5541, 422, 1234, 18, 15330, 13, 203, 3639, 288, 203, 5411, 1142, 2988, 273, 1674, 31, 203, 5411, 1142, 5541, 273, 1234, 18, 15330, 31, 203, 3639, 289, 203, 203, 377, 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 ]
pragma solidity ^0.4.24; import "./Identity.sol"; contract IdentityFactory { event IdentityCreated(Identity _identity, address _owner, uint _createdAt); function create(address _owner) external returns (Identity) { Identity identity = new Identity(_owner); emit IdentityCreated(identity, _owner, block.timestamp); // solium-disable-line security/no-block-members return identity; } }
solium-disable-line security/no-block-members
emit IdentityCreated(identity, _owner, block.timestamp);
6,421,501
[ 1, 18281, 5077, 17, 8394, 17, 1369, 4373, 19, 2135, 17, 2629, 17, 7640, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 3626, 7808, 6119, 12, 10781, 16, 389, 8443, 16, 1203, 18, 5508, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xf567Bc19381aA04fB235B4ABBBC4a51ac175A233/sources/YAMDelegate.sol
* @dev Transfer tokens to a specified address. @param to The address to transfer to. @param value The amount to be transferred. @return True on success, false otherwise./ underlying balance is stored in yams, so divide by current scaling factor note, this means as scaling factor grows, dust will be untransferrable. minimum transfer value == yamsScalingFactor / 1e24; get amount in underlying sub from balance of sender add to balance of receiver
function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { uint256 yamValue = value.mul(internalDecimals).div(yamsScalingFactor); _yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue); _yamBalances[to] = _yamBalances[to].add(yamValue); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], yamValue); return true; }
3,489,224
[ 1, 5912, 2430, 358, 279, 1269, 1758, 18, 225, 358, 1021, 1758, 358, 7412, 358, 18, 225, 460, 1021, 3844, 358, 506, 906, 4193, 18, 327, 1053, 603, 2216, 16, 629, 3541, 18, 19, 6808, 11013, 353, 4041, 316, 677, 301, 87, 16, 1427, 12326, 635, 783, 10612, 5578, 4721, 16, 333, 4696, 487, 10612, 5578, 314, 3870, 16, 302, 641, 903, 506, 640, 13866, 354, 7119, 18, 5224, 7412, 460, 422, 677, 301, 87, 8471, 6837, 342, 404, 73, 3247, 31, 336, 3844, 316, 6808, 720, 628, 11013, 434, 5793, 527, 358, 11013, 434, 5971, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 203, 3639, 3903, 203, 3639, 923, 18241, 12, 869, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 203, 203, 3639, 2254, 5034, 677, 301, 620, 273, 460, 18, 16411, 12, 7236, 31809, 2934, 2892, 12, 93, 301, 87, 8471, 6837, 1769, 203, 203, 3639, 389, 93, 301, 38, 26488, 63, 3576, 18, 15330, 65, 273, 389, 93, 301, 38, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 93, 301, 620, 1769, 203, 203, 3639, 389, 93, 301, 38, 26488, 63, 869, 65, 273, 389, 93, 301, 38, 26488, 63, 869, 8009, 1289, 12, 93, 301, 620, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 203, 3639, 389, 8501, 15608, 815, 24899, 3771, 1332, 815, 63, 3576, 18, 15330, 6487, 389, 3771, 1332, 815, 63, 869, 6487, 677, 301, 620, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x9aA7a5e3E5e963A540648927B2e34DEEc95cbB0c/sources/contracts/randomgenerator.sol
TODO needs insert function that maintains order. TODO needs NatSpec documentation comment.* Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index/
function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) { require( set_._values.length > index_ ); require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." ); bytes32 existingValue_ = _at( set_, index_ ); set_._values[index_] = valueToInsert_; return _add( set_, existingValue_); }
4,523,127
[ 1, 6241, 4260, 2243, 445, 716, 11566, 4167, 1353, 18, 2660, 4260, 423, 270, 1990, 7323, 2879, 18, 8040, 87, 394, 460, 635, 12499, 2062, 460, 622, 2112, 770, 358, 679, 434, 526, 471, 3637, 2112, 460, 622, 2112, 770, 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, 389, 6387, 12, 694, 2502, 444, 67, 16, 2254, 5034, 770, 67, 16, 1731, 1578, 30605, 4600, 67, 262, 3238, 1135, 261, 1426, 262, 288, 203, 3639, 2583, 12, 225, 444, 67, 6315, 2372, 18, 2469, 405, 770, 67, 11272, 203, 3639, 2583, 12, 401, 67, 12298, 12, 444, 67, 16, 30605, 4600, 67, 262, 16, 315, 3288, 460, 1846, 14302, 358, 2243, 309, 1846, 14302, 358, 19427, 526, 1199, 11272, 203, 3639, 1731, 1578, 2062, 620, 67, 273, 389, 270, 12, 444, 67, 16, 770, 67, 11272, 203, 3639, 444, 67, 6315, 2372, 63, 1615, 67, 65, 273, 30605, 4600, 67, 31, 203, 3639, 327, 389, 1289, 12, 444, 67, 16, 2062, 620, 67, 1769, 203, 565, 289, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../interfaces/IControlledManagedPool.sol"; import "./BasePoolController.sol"; /** * @dev Pool controller that serves as the "owner" of a Managed pool, and is in turn owned by * an account empowered to make calls on this contract, which are forwarded to the underlyling pool. * * This contract can place limits on whether and how these calls can be made. For instance, * imposing a minimum gradual weight change duration. * * While Balancer pool owners are immutable, ownership of this pool controller can be transferrable, * if the corresponding permission is set. */ contract ManagedPoolController is BasePoolController, IControlledManagedPool { using WordCodec for bytes32; // There are five managed pool rights: all corresponding to permissioned functions of ManagedPool. struct ManagedPoolRights { bool canChangeWeights; bool canDisableSwaps; bool canSetMustAllowlistLPs; bool canSetCircuitBreakers; bool canChangeTokens; } // The minimum weight change duration could be replaced with more sophisticated rate-limiting. uint256 internal immutable _minWeightChangeDuration; // Immutable controller state - the first 16 bits are reserved as a bitmap for permission flags // (3 used in the base class; 5 used here), and the remaining 240 bits can be used by derived classes // to store any other immutable data. // // Managed Pool Controller Permissions | Base Controller Permissions ] // [ 240 | 8 bits | 1 bit | 1 bit | 1 bit | 1 bit | 1 bit | 1 bit | 1 bit | 1 bit ] // [unused|reserved| tokens | breakers | LPs | swaps | weights | metadata | swap fee | transfer ] // |MSB LSB| uint256 private constant _CHANGE_WEIGHTS_OFFSET = 3; uint256 private constant _DISABLE_SWAPS_OFFSET = 4; uint256 private constant _MUST_ALLOWLIST_LPS_OFFSET = 5; uint256 private constant _CIRCUIT_BREAKERS_OFFSET = 6; uint256 private constant _CHANGE_TOKENS_OFFSET = 7; /** * @dev Pass in the `BasePoolRights` and `ManagedPoolRights` structures, to form the complete set of * immutable rights. Then pass any parameters related to restrictions on those rights. For instance, * a minimum duration if changing weights is enabled. */ constructor( BasePoolRights memory baseRights, ManagedPoolRights memory managedRights, uint256 minWeightChangeDuration, address manager ) BasePoolController(encodePermissions(baseRights, managedRights), manager) { _minWeightChangeDuration = minWeightChangeDuration; } function encodePermissions(BasePoolRights memory baseRights, ManagedPoolRights memory managedRights) public pure returns (bytes32) { bytes32 permissions = super.encodePermissions(baseRights); return permissions .insertBool(managedRights.canChangeWeights, _CHANGE_WEIGHTS_OFFSET) .insertBool(managedRights.canDisableSwaps, _DISABLE_SWAPS_OFFSET) .insertBool(managedRights.canSetMustAllowlistLPs, _MUST_ALLOWLIST_LPS_OFFSET) .insertBool(managedRights.canChangeTokens, _CHANGE_TOKENS_OFFSET) .insertBool(managedRights.canSetCircuitBreakers, _CIRCUIT_BREAKERS_OFFSET); } /** * @dev Getter for the canChangeWeights permission. */ function canChangeWeights() public view returns (bool) { return _controllerState.decodeBool(_CHANGE_WEIGHTS_OFFSET); } /** * @dev Getter for the canDisableSwaps permission. */ function canDisableSwaps() public view returns (bool) { return _controllerState.decodeBool(_DISABLE_SWAPS_OFFSET); } /** * @dev Getter for the mustAllowlistLPs permission. */ function canSetMustAllowlistLPs() public view returns (bool) { return _controllerState.decodeBool(_MUST_ALLOWLIST_LPS_OFFSET); } /** * @dev Getter for the canSetCircuitBreakers permission. */ function canSetCircuitBreakers() public view returns (bool) { return _controllerState.decodeBool(_CIRCUIT_BREAKERS_OFFSET); } /** * @dev Getter for the canChangeTokens permission. */ function canChangeTokens() public view returns (bool) { return _controllerState.decodeBool(_CHANGE_TOKENS_OFFSET); } /** * @dev Getter for the minimum weight change duration. */ function getMinWeightChangeDuration() external view returns (uint256) { return _minWeightChangeDuration; } /** * @dev Update weights linearly from the current values to the given end weights, between startTime * and endTime. */ function updateWeightsGradually( uint256 startTime, uint256 endTime, uint256[] calldata endWeights ) external virtual override onlyManager withBoundPool { _require(canChangeWeights(), Errors.UNAUTHORIZED_OPERATION); _require( endTime >= startTime && endTime - startTime >= _minWeightChangeDuration, Errors.WEIGHT_CHANGE_TOO_FAST ); IControlledManagedPool(pool).updateWeightsGradually(startTime, endTime, endWeights); } /** * @dev Pass a call to ManagedPool's setSwapEnabled through to the underlying pool. */ function setSwapEnabled(bool swapEnabled) external virtual override onlyManager withBoundPool { _require(canDisableSwaps(), Errors.UNAUTHORIZED_OPERATION); IControlledManagedPool(pool).setSwapEnabled(swapEnabled); } /** * @dev Pass a call to ManagedPool's setMustAllowlistLPs through to the underlying pool. This could * be restricted in various ways. For instance, we could allow it to change state only once, or only * in one direction, but there seems to be no compelling reason to do so in the reference controller. * * Deploying a Managed Pool with an empty allowlist could function like an LBP, or a smart treasury. * Adding a set of addresses to the allowlist enables multiple seed funding sources. Disabling the * allowlist, or re-enabling it after allowing public LPs, can impose or remove a "cap" on the total supply. */ function setMustAllowlistLPs(bool mustAllowlistLPs) external virtual override onlyManager withBoundPool { _require(canSetMustAllowlistLPs(), Errors.UNAUTHORIZED_OPERATION); IControlledManagedPool(pool).setMustAllowlistLPs(mustAllowlistLPs); } /** * @dev Pass a call to ManagedPool's addAllowedAddress through to the underlying pool. * The underlying pool handles all state/permission checks. It will revert if the LP allowlist is off. */ function addAllowedAddress(address member) external virtual override onlyManager withBoundPool { IControlledManagedPool(pool).addAllowedAddress(member); } /** * @dev Pass a call to ManagedPool's removeAllowedAddress through to the underlying pool. * The underlying pool handles all state/permission checks. It will revert if the address was not * previouslly added to the allowlist. */ function removeAllowedAddress(address member) external virtual override onlyManager withBoundPool { IControlledManagedPool(pool).removeAllowedAddress(member); } /** * @dev Pass a call to ManagedPool's withdrawCollectedManagementFees through to the underlying pool. */ function withdrawCollectedManagementFees(address recipient) external virtual override onlyManager withBoundPool { IControlledManagedPool(pool).withdrawCollectedManagementFees(recipient); } }
* @dev Getter for the minimum weight change duration./
function getMinWeightChangeDuration() external view returns (uint256) { return _minWeightChangeDuration; }
5,437,187
[ 1, 8461, 364, 326, 5224, 3119, 2549, 3734, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9555, 6544, 3043, 5326, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 1154, 6544, 3043, 5326, 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 ]
./full_match/80001/0x3d55Cc514ddEECbb73eB9Ff193e463ed35a45071/sources/contracts/protocol/modules/DextfTradeModule.sol
* Makes sure that the requested outbound components do not exceed the current positions @param _fund Address of the fund subject of the trade/ Transfer the outbound components Compute the available component for the given quantity Check that we have enough tokens to perform the outbound trade Check that the tokens are actually in the vault
function _checkTradeOutboundComponents( ISetToken _fund, uint256 _quantity, TradeComponent[] memory _scaledOutboundComponents, uint256[] memory preTradeOutboundBalances ) internal view { for (uint256 i = 0; i < _scaledOutboundComponents.length; i++) { uint256 unit = _fund .getDefaultPositionRealUnit(_scaledOutboundComponents[i].componentAddress) .toUint256(); uint256 availableQuantity = _quantity.preciseMul(unit); uint256 tradeRealUnits = _scaledOutboundComponents[i].tradeRealUnits; require(tradeRealUnits <= availableQuantity, "Insufficient holdings for trade"); require(tradeRealUnits <= preTradeOutboundBalances[i], "Insufficient balance for trade"); } }
5,576,462
[ 1, 14534, 3071, 716, 326, 3764, 11663, 4085, 741, 486, 9943, 326, 783, 6865, 225, 389, 74, 1074, 565, 5267, 434, 326, 284, 1074, 3221, 434, 326, 18542, 19, 12279, 326, 11663, 4085, 8155, 326, 2319, 1794, 364, 326, 864, 10457, 2073, 716, 732, 1240, 7304, 2430, 358, 3073, 326, 11663, 18542, 2073, 716, 326, 2430, 854, 6013, 316, 326, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 1893, 22583, 17873, 7171, 12, 203, 565, 467, 694, 1345, 389, 74, 1074, 16, 203, 565, 2254, 5034, 389, 16172, 16, 203, 565, 2197, 323, 1841, 8526, 3778, 389, 20665, 17873, 7171, 16, 203, 565, 2254, 5034, 8526, 3778, 675, 22583, 17873, 38, 26488, 203, 225, 262, 2713, 1476, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 20665, 17873, 7171, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2254, 5034, 2836, 273, 389, 74, 1074, 203, 1377, 263, 588, 1868, 2555, 6955, 2802, 24899, 20665, 17873, 7171, 63, 77, 8009, 4652, 1887, 13, 203, 1377, 263, 869, 5487, 5034, 5621, 203, 1377, 2254, 5034, 2319, 12035, 273, 389, 16172, 18, 4036, 784, 27860, 12, 4873, 1769, 203, 1377, 2254, 5034, 18542, 6955, 7537, 273, 389, 20665, 17873, 7171, 63, 77, 8009, 20077, 6955, 7537, 31, 203, 203, 1377, 2583, 12, 20077, 6955, 7537, 1648, 2319, 12035, 16, 315, 5048, 11339, 6887, 899, 364, 18542, 8863, 203, 1377, 2583, 12, 20077, 6955, 7537, 1648, 675, 22583, 17873, 38, 26488, 63, 77, 6487, 315, 5048, 11339, 11013, 364, 18542, 8863, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2fB140574f02b3043a7B2342017f7E1A3a4f98Cb/sources/contracts/PoolPositionBaseSlim.sol
@inheritdoc IPoolPositionSlim
function binLpAddAmountRequirement(uint128 binZeroLpAddAmount) external view checkBin returns (IPool.RemoveLiquidityParams[] memory params) { params = _binLpAddAmountRequirement(binZeroLpAddAmount); }
3,849,600
[ 1, 36, 10093, 467, 2864, 2555, 3738, 381, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4158, 48, 84, 986, 6275, 18599, 12, 11890, 10392, 4158, 7170, 48, 84, 986, 6275, 13, 3903, 1476, 866, 9913, 1135, 261, 2579, 1371, 18, 3288, 48, 18988, 24237, 1370, 8526, 3778, 859, 13, 288, 203, 3639, 859, 273, 389, 4757, 48, 84, 986, 6275, 18599, 12, 4757, 7170, 48, 84, 986, 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 ]
pragma solidity 0.5.12; import "./Handler.sol"; import "./interface/ICompound.sol"; import "./library/ReentrancyGuard.sol"; contract CompoundHandler is Handler, ReentrancyGuard { uint256 constant BASE = 10**18; struct InterestDetails { uint256 totalUnderlyingBalance; // Total underlying balance including interest uint256 interest; // Total interest } // Based on underlying token, get current interest details mapping(address => InterestDetails) public interestDetails; mapping(address => address) public cTokens; //cTokens; address public compAddress; event NewMappingcToken( address indexed token, address indexed mappingcToken ); event CompClaimed( address indexed _underlyingToken, uint256 indexed compBalance ); constructor(address _dTokenController, address _compAddress) public { initialize(_dTokenController, _compAddress); } // --- Init --- // This function is used with contract proxy, do not modify this function. function initialize(address _dTokenController, address _compAddress) public { super.initialize(_dTokenController); compAddress = _compAddress; initReentrancyStatus(); } /** * @dev Authorized function to set cToken address base on underlying token. * @param _underlyingTokens Supports underlying tokens in Compound. * @param _mappingTokens Corresponding cToken addresses. */ function setcTokensRelation( address[] calldata _underlyingTokens, address[] calldata _mappingTokens ) external auth { require( _underlyingTokens.length == _mappingTokens.length, "setTokensRelation: Array length do not match!" ); for (uint256 i = 0; i < _underlyingTokens.length; i++) { _setcTokenRelation(_underlyingTokens[i], _mappingTokens[i]); } } function _setcTokenRelation( address _underlyingToken, address _mappingcToken ) internal { cTokens[_underlyingToken] = _mappingcToken; emit NewMappingcToken(_underlyingToken, _mappingcToken); } /** * @dev Authorized function to approves market and dToken to transfer handler's underlying token. * @param _underlyingToken Token address to approve. */ function approve(address _underlyingToken, uint256 amount) public auth { address _cToken = cTokens[_underlyingToken]; require( doApprove(_underlyingToken, _cToken, amount), "approve: Approve cToken failed!" ); super.approve(_underlyingToken, amount); } /** * @dev Internal function to transfer COMP airdrops to corresponding dToken to distribute. */ function claimComp(address _underlyingToken) internal { uint256 compBalance = IERC20(compAddress).balanceOf(address(this)); if (compBalance > 0) { address _dToken = IDTokenController(dTokenController).getDToken( _underlyingToken ); require( doTransferOut(compAddress, _dToken, compBalance), "deposit: Comp transfer out of contract failed." ); emit CompClaimed(_underlyingToken, compBalance); } } /** * @dev Deposit token to market, only called by dToken contract. * @param _underlyingToken Token to deposit. * @return The actual deposited token amount. */ function deposit(address _underlyingToken, uint256 _amount) external whenNotPaused auth nonReentrant returns (uint256) { require( tokenIsEnabled(_underlyingToken), "deposit: Token is disabled!" ); require( _amount > 0, "deposit: Deposit amount should be greater than 0!" ); address _cToken = cTokens[_underlyingToken]; require(_cToken != address(0x0), "deposit: Do not support token!"); uint256 _MarketBalanceBefore = ICompound(_cToken).balanceOfUnderlying( address(this) ); // Update the stored interest with the market balance before the mint InterestDetails storage _details = interestDetails[_underlyingToken]; uint256 _interest = _MarketBalanceBefore.sub( _details.totalUnderlyingBalance ); _details.interest = _details.interest.add(_interest); // Mint all the token balance of the handler, // which should be the exact deposit amount normally, // but there could be some unexpected transfers before. uint256 _handlerBalance = IERC20(_underlyingToken).balanceOf( address(this) ); require( ICompound(_cToken).mint(_handlerBalance) == 0, "deposit: Fail to supply to compound!" ); claimComp(_underlyingToken); // including unexpected transfers. uint256 _MarketBalanceAfter = ICompound(_cToken).balanceOfUnderlying( address(this) ); // Store the latest real balance. _details.totalUnderlyingBalance = _MarketBalanceAfter; uint256 _changedAmount = _MarketBalanceAfter.sub(_MarketBalanceBefore); // Return the smaller value as unexpected transfers were also included. return _changedAmount > _amount ? _amount : _changedAmount; } /** * @dev Withdraw token from market, but only for dToken contract. * @param _underlyingToken Token to withdraw. * @param _amount Token amount to withdraw. * @return The actual withdrown token amount. */ function withdraw(address _underlyingToken, uint256 _amount) external whenNotPaused auth nonReentrant returns (uint256) { require( _amount > 0, "withdraw: Withdraw amount should be greater than 0!" ); address _cToken = cTokens[_underlyingToken]; require(_cToken != address(0x0), "withdraw: Do not support token!"); uint256 _MarketBalanceBefore = ICompound(_cToken).balanceOfUnderlying( address(this) ); // Update the stored interest with the market balance before the redeem InterestDetails storage _details = interestDetails[_underlyingToken]; uint256 _interest = _MarketBalanceBefore.sub( _details.totalUnderlyingBalance ); _details.interest = _details.interest.add(_interest); uint256 _handlerBalanceBefore = IERC20(_underlyingToken).balanceOf( address(this) ); // Redeem all or just the amount of underlying token if (_amount == uint256(-1)) { require( ICompound(_cToken).redeem( IERC20(_cToken).balanceOf(address(this)) ) == 0, "withdraw: Fail to withdraw from market!" ); } else { require( ICompound(_cToken).redeemUnderlying(_amount) == 0, "withdraw: Fail to withdraw from market!" ); } claimComp(_underlyingToken); uint256 _handlerBalanceAfter = IERC20(_underlyingToken).balanceOf( address(this) ); // Store the latest real balance. _details.totalUnderlyingBalance = ICompound(_cToken) .balanceOfUnderlying(address(this)); uint256 _changedAmount = _handlerBalanceAfter.sub( _handlerBalanceBefore ); // return a smaller value. return _changedAmount > _amount ? _amount : _changedAmount; } /** * @dev Update exchange rate in cToken and get the latest total balance for * handler's _underlyingToken, with all accumulated interest included. * @param _underlyingToken Token to get actual balance. */ function getRealBalance(address _underlyingToken) external returns (uint256) { return ICompound(cTokens[_underlyingToken]).balanceOfUnderlying( address(this) ); } /** * @dev The latest maximum withdrawable _underlyingToken in the market. * @param _underlyingToken Token to get liquidity. */ function getRealLiquidity(address _underlyingToken) external returns (uint256) { address _cToken = cTokens[_underlyingToken]; uint256 _underlyingBalance = ICompound(_cToken).balanceOfUnderlying( address(this) ); uint256 _cash = ICompound(_cToken).getCash(); return _underlyingBalance > _cash ? _cash : _underlyingBalance; } /***************************************************/ /*** View Interfaces For Backwards compatibility ***/ /***************************************************/ /** * @dev Total balance of handler's _underlyingToken, accumulated interest included * @param _underlyingToken Token to get balance. */ function getBalance(address _underlyingToken) public view returns (uint256) { address _cToken = cTokens[_underlyingToken]; uint256 _cTokenBalance; uint256 _exchangeRate; uint256 _error; (_error, _cTokenBalance, , _exchangeRate) = ICompound(_cToken) .getAccountSnapshot(address(this)); if (_error != 0) { return 0; } return _cTokenBalance.mul(_exchangeRate) / BASE; } /** * @dev The maximum withdrawable amount of _underlyingToken in the market. * @param _underlyingToken Token to get liquidity. */ function getLiquidity(address _underlyingToken) external view returns (uint256) { address _cToken = cTokens[_underlyingToken]; uint256 _underlyingBalance = getBalance(_underlyingToken); uint256 _cash = ICompound(_cToken).getCash(); return _underlyingBalance > _cash ? _cash : _underlyingBalance; } }
* @dev Authorized function to approves market and dToken to transfer handler's underlying token. @param _underlyingToken Token address to approve./
function approve(address _underlyingToken, uint256 amount) public auth { address _cToken = cTokens[_underlyingToken]; require( doApprove(_underlyingToken, _cToken, amount), "approve: Approve cToken failed!" ); super.approve(_underlyingToken, amount); }
6,398,384
[ 1, 15341, 445, 358, 6617, 3324, 13667, 471, 302, 1345, 358, 7412, 1838, 1807, 6808, 1147, 18, 225, 389, 9341, 6291, 1345, 3155, 1758, 358, 6617, 537, 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, 565, 445, 6617, 537, 12, 2867, 389, 9341, 6291, 1345, 16, 2254, 5034, 3844, 13, 1071, 1357, 288, 203, 3639, 1758, 389, 71, 1345, 273, 276, 5157, 63, 67, 9341, 6291, 1345, 15533, 203, 203, 3639, 2583, 12, 203, 5411, 741, 12053, 537, 24899, 9341, 6291, 1345, 16, 389, 71, 1345, 16, 3844, 3631, 203, 5411, 315, 12908, 537, 30, 1716, 685, 537, 276, 1345, 2535, 4442, 203, 3639, 11272, 203, 203, 3639, 2240, 18, 12908, 537, 24899, 9341, 6291, 1345, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract StakeContract is Initializable { mapping(bytes32 => uint256) public user_time_created; mapping(bytes32 => uint256) public user_coin_staked; mapping(address => uint256) public user_num_stakes; uint[] private stake_price_by_day; uint256 public daily_award; uint256 public total_coin_staked; uint256 public deploy_time; uint256 public last_award_offset; uint256 public day_length; uint256 public lock_period; uint256 public total_period; address public creaticles_address; function initialize(address _creaticles_address, uint256 _day_length, uint256 _lock_period, uint256 _daily_reward, uint256 _total_period, uint256 _deploy_time) public initializer { creaticles_address = _creaticles_address; stake_price_by_day.push(0); daily_award = _daily_reward; total_coin_staked = 0; total_period = _total_period; day_length = _day_length; deploy_time = _deploy_time; // day last_award_offset = 0; lock_period = _lock_period; // TODO add end to staking period // uint a = 4; // uint b = 5; // uint c = a - b; // console.log(c); } function hash_of_user_stake(address user, uint256 stake_id) private pure returns (bytes32 hash) { return keccak256(abi.encodePacked(user, stake_id)); } function stake(uint256 stake_id, uint256 amount) public returns (uint256 amount_staked) { require(stake_id < 10000, "No more than 10000 stakes per user"); require(block.timestamp <= deploy_time + day_length * total_period, "Cannot stake after end of reward period"); bytes32 user_hash = hash_of_user_stake(msg.sender, stake_id); // add coin to staking - this coin acrues interest each day require(amount > 0, "Cannot stake zero coin"); require(user_coin_staked[user_hash] == 0, "Can only have one stake at once for stake id"); check_increment_day(); // if this next statement succeeds, we will have received Creaticles token payment IERC20(creaticles_address).transferFrom(msg.sender, address(this), amount); total_coin_staked = total_coin_staked + amount; user_coin_staked[user_hash] = amount; user_time_created[user_hash] = block.timestamp > deploy_time ? block.timestamp : deploy_time; // keep track of largest stake id we have seen so far uint256 num_stakes = user_num_stakes[msg.sender]; user_num_stakes[msg.sender] = num_stakes >= stake_id + 1 ? num_stakes : stake_id + 1; return amount; } function unstake(uint256 stake_id, uint256 amount) public returns (uint256 amount_staked) { require(stake_id < 10000, "No more than 10000 stakes per user"); bytes32 user_hash = hash_of_user_stake(msg.sender, stake_id); uint256 buy_amount = user_coin_staked[user_hash]; require(amount <= buy_amount, "Cannot unstake more than you staked"); require(amount > 0, "Cannot unstake zero coin"); uint256 profit = 0; // remove coin from staking - if longer than lockup period we acrue interest check_increment_day(); if (block.timestamp > deploy_time) { // offset is number of days since deployment, rounded down uint256 current_offset = (block.timestamp - deploy_time) / day_length; uint256 buy_offset = (user_time_created[user_hash] - deploy_time) / day_length; uint256 prev_price = stake_price_by_day[buy_offset]; uint256 current_price = stake_price_by_day[current_offset]; profit = amount * (current_price - prev_price); if (current_offset - buy_offset < lock_period) { profit = 0; // they did not wait long enough, we simply give them their coin back } } console.log("Sending unstake profit: ", profit); user_coin_staked[user_hash] = buy_amount - amount; total_coin_staked = total_coin_staked - amount; IERC20(creaticles_address).transfer(msg.sender, amount + profit); return buy_amount - amount; } function increment_day() internal { // give award to users since we have reached a new day - we award 100k tokens to the community! uint256 current_offset = (block.timestamp - deploy_time) / day_length; uint256 day_diff = current_offset - last_award_offset; uint256 reward_per_token = 0; if (total_coin_staked > 0) { reward_per_token = daily_award / total_coin_staked; } console.log("Old stake price: ", stake_price_by_day[stake_price_by_day.length - 1]); for(uint256 i = 0; i < day_diff; i++) { uint256 prev_price = stake_price_by_day[stake_price_by_day.length - 1]; uint256 new_price = prev_price + reward_per_token; if (stake_price_by_day.length <= total_period) { stake_price_by_day.push(new_price); } else { // once we reach the end of the total period, we stop increasing the daily price (and therefore the profit from withdrawing) stake_price_by_day.push(prev_price); } } console.log("New stake price: ", stake_price_by_day[stake_price_by_day.length - 1]); last_award_offset = current_offset; } function number_of_stakes(address user) public view returns (uint256 num_stakes) { return user_num_stakes[user]; } function check_increment_day() public { // this forces an update of day so we can check interest if (block.timestamp >= deploy_time) { uint256 current_offset = (block.timestamp - deploy_time) / day_length; console.log("Number of days since deployment: ", current_offset); if (current_offset > last_award_offset) { increment_day(); } } } function profile(address user, uint256 stake_id) public view returns (uint256 timestamp, uint256 tokens_staked, uint256 interest, bool locked) { // show information about staked coin for a user address // not that interest information only updates after the first user stakes or unstakes on a given day // this function only views interest, does not compute updated interest // require(user_coin_staked[user] > 0, "User must have staked coin to view profile"); require(stake_id < 10000, "No more than 10000 stakes per user"); bytes32 user_hash = hash_of_user_stake(user, stake_id); if (user_coin_staked[user_hash] == 0) { return (0, 0, 0, true); } uint256 buy_time = user_time_created[user_hash]; uint256 current_user_coin_staked = user_coin_staked[user_hash]; uint256 profit = 0; bool user_locked = true; if (block.timestamp > deploy_time) { uint256 current_offset = (block.timestamp - deploy_time) / day_length; uint256 amount = user_coin_staked[user_hash]; uint256 buy_offset = (buy_time - deploy_time) / day_length; uint256 prev_price = stake_price_by_day[buy_offset]; uint256 current_price = stake_price_by_day[current_offset]; user_locked = (current_offset - buy_offset < lock_period); profit = amount * (current_price - prev_price); } return (buy_time, current_user_coin_staked, profit, user_locked); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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); }
remove coin from staking - if longer than lockup period we acrue interest offset is number of days since deployment, rounded down
function unstake(uint256 stake_id, uint256 amount) public returns (uint256 amount_staked) { require(stake_id < 10000, "No more than 10000 stakes per user"); bytes32 user_hash = hash_of_user_stake(msg.sender, stake_id); uint256 buy_amount = user_coin_staked[user_hash]; require(amount <= buy_amount, "Cannot unstake more than you staked"); require(amount > 0, "Cannot unstake zero coin"); uint256 profit = 0; check_increment_day(); if (block.timestamp > deploy_time) { uint256 current_offset = (block.timestamp - deploy_time) / day_length; uint256 buy_offset = (user_time_created[user_hash] - deploy_time) / day_length; uint256 prev_price = stake_price_by_day[buy_offset]; uint256 current_price = stake_price_by_day[current_offset]; profit = amount * (current_price - prev_price); if (current_offset - buy_offset < lock_period) { } } console.log("Sending unstake profit: ", profit); user_coin_staked[user_hash] = buy_amount - amount; total_coin_staked = total_coin_staked - amount; IERC20(creaticles_address).transfer(msg.sender, amount + profit); return buy_amount - amount; }
7,855
[ 1, 4479, 13170, 628, 384, 6159, 300, 309, 7144, 2353, 2176, 416, 3879, 732, 1721, 86, 344, 16513, 1384, 353, 1300, 434, 4681, 3241, 6314, 16, 16729, 2588, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 334, 911, 12, 11890, 5034, 384, 911, 67, 350, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 11890, 5034, 3844, 67, 334, 9477, 13, 288, 203, 3639, 2583, 12, 334, 911, 67, 350, 411, 12619, 16, 315, 2279, 1898, 2353, 12619, 384, 3223, 1534, 729, 8863, 203, 3639, 1731, 1578, 729, 67, 2816, 273, 1651, 67, 792, 67, 1355, 67, 334, 911, 12, 3576, 18, 15330, 16, 384, 911, 67, 350, 1769, 203, 3639, 2254, 5034, 30143, 67, 8949, 273, 729, 67, 12645, 67, 334, 9477, 63, 1355, 67, 2816, 15533, 203, 203, 3639, 2583, 12, 8949, 1648, 30143, 67, 8949, 16, 315, 4515, 640, 334, 911, 1898, 2353, 1846, 384, 9477, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 4515, 640, 334, 911, 3634, 13170, 8863, 203, 203, 3639, 2254, 5034, 450, 7216, 273, 374, 31, 203, 203, 3639, 866, 67, 15016, 67, 2881, 5621, 203, 3639, 309, 261, 2629, 18, 5508, 405, 7286, 67, 957, 13, 288, 203, 5411, 2254, 5034, 783, 67, 3348, 273, 261, 2629, 18, 5508, 300, 7286, 67, 957, 13, 342, 2548, 67, 2469, 31, 203, 5411, 2254, 5034, 30143, 67, 3348, 273, 261, 1355, 67, 957, 67, 4824, 63, 1355, 67, 2816, 65, 300, 7286, 67, 957, 13, 342, 2548, 67, 2469, 31, 203, 203, 5411, 2254, 5034, 2807, 67, 8694, 273, 384, 911, 67, 8694, 67, 1637, 67, 2881, 63, 70, 9835, 67, 3348, 15533, 203, 5411, 2254, 5034, 783, 67, 8694, 273, 384, 911, 67, 8694, 67, 1637, 67, 2881, 2 ]
./full_match/11155111/0xbE3d97A00b4bE98A626a5c6DEc64f74F5F28da1f/sources/contracts/honeycast.sol
* @dev See {ERC721-_burn}. This override additionally checks to see if a token-specific URI was set for the token, and if so, it deletes the token URI from the storage mapping./
function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } }
3,815,549
[ 1, 9704, 288, 654, 39, 27, 5340, 17, 67, 70, 321, 5496, 1220, 3849, 2719, 1230, 4271, 358, 2621, 309, 279, 1147, 17, 12524, 3699, 1703, 444, 364, 326, 1147, 16, 471, 309, 1427, 16, 518, 9792, 326, 1147, 3699, 628, 326, 2502, 2874, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 445, 389, 70, 321, 12, 11890, 5034, 1147, 548, 13, 2713, 5024, 3849, 288, 203, 1850, 2240, 6315, 70, 321, 12, 2316, 548, 1769, 203, 21281, 1850, 309, 261, 3890, 24899, 2316, 1099, 2520, 63, 2316, 548, 65, 2934, 2469, 480, 374, 13, 288, 203, 2868, 1430, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 1850, 289, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockRHegic is ERC20("Mock rHEGIC", "MockRHEGIC") { constructor() {} function mint(uint amount) external { _mint(msg.sender, amount); } // Need to make the bytecode different from that of Mock HEGIC // otherwise Hardhat can't verify it on etherscan function isIOU() external pure returns (bool) { return true; } }
Need to make the bytecode different from that of Mock HEGIC otherwise Hardhat can't verify it on etherscan
function isIOU() external pure returns (bool) { return true; }
1,079,515
[ 1, 14112, 358, 1221, 326, 22801, 3775, 628, 716, 434, 7867, 4194, 43, 2871, 3541, 670, 1060, 11304, 848, 1404, 3929, 518, 603, 13750, 414, 4169, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 353, 4294, 57, 1435, 3903, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x68B56567AF308FE8d94876AB0fE88541ED025e1C/sources/stkCvxCrvDistributorZaps.sol
@notice Claim from distributor as cvxCrv @param index - claimer index @param account - claimer account @param amount - claim amount @param merkleProof - merkle proof for the claim @param to - address to send withdrawn underlying to @return amount of underlying withdrawn
) external returns (uint256) { _claim(index, account, amount, merkleProof); return IGenericVault(vault).withdrawAll(to); }
4,390,567
[ 1, 9762, 628, 1015, 19293, 487, 8951, 14626, 4962, 225, 770, 300, 927, 69, 4417, 770, 225, 2236, 300, 927, 69, 4417, 2236, 225, 3844, 300, 7516, 3844, 225, 30235, 20439, 300, 30235, 14601, 364, 326, 7516, 225, 358, 300, 1758, 358, 1366, 598, 9446, 82, 6808, 358, 327, 3844, 434, 6808, 598, 9446, 82, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 389, 14784, 12, 1615, 16, 2236, 16, 3844, 16, 30235, 20439, 1769, 203, 3639, 327, 467, 7014, 12003, 12, 26983, 2934, 1918, 9446, 1595, 12, 869, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "../ERC20.sol"; /** * @dev ERC20 token where the admin can control what's approvable */ abstract contract ERC20Approvable is ERC20 { bool private _approved = true; /** * @dev Returns true if approvable */ function isApprovable() public virtual view returns(bool) { return _approved; } /** * @dev Checks to see if appprovable before approving */ function _approve( address owner, address spender, uint256 amount ) internal virtual override { if (!_approved) revert InvalidCall(); super._approve(owner, spender, amount); } /** * @dev Allows or denies tokens to be approvable */ function _approvable(bool yes) internal virtual { _approved = yes; } }
* @dev Returns true if approvable/
function isApprovable() public virtual view returns(bool) { return _approved; }
1,783,766
[ 1, 1356, 638, 309, 6617, 16845, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 353, 12053, 16845, 1435, 1071, 5024, 1476, 1135, 12, 6430, 13, 288, 203, 565, 327, 389, 25990, 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 ]
pragma solidity 0.5.16; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./EthAddressLib.sol"; contract FlashExchange is Ownable { using SafeMath for uint256; uint256 constant FLASHLOAN_LP_YIELD = 18; //18 bps flashloan yield uint256 constant FLASHLOAN_LP_YIELD_BASE = 1000; //basis points mapping(address => bool) flashboys; mapping(address => uint256) assetsMaxYield; modifier onlyFlashboys { require(flashboys[msg.sender], "Only flashboys can call this function"); _; } function addFlashboys(address[] memory _flashboys) public onlyOwner { for (uint256 i = 0; i < _flashboys.length; i++) { flashboys[_flashboys[i]] = true; } } function addAsset(address _asset, uint256 _maxYield) public onlyOwner { assetsMaxYield[_asset] = _maxYield; } function exchange(address _asset, uint256 _amount) public payable onlyFlashboys { uint256 yield = _amount.mul(FLASHLOAN_LP_YIELD).div( FLASHLOAN_LP_YIELD_BASE ); require(yield <= assetsMaxYield[_asset], "Flashloan is too big"); if (_asset == EthAddressLib.ethAddress()) { require(msg.value == _amount, "The value sent is not enough"); msg.sender.transfer(_amount.add(yield)); } else { //simulating exchange pulling funds from the wallet require( IERC20(_asset).transferFrom(msg.sender, address(this), _amount) ); require(IERC20(_asset).transfer(msg.sender, _amount.add(yield))); } } function() external payable {} function withdraw(address _asset) public onlyOwner { if (_asset == EthAddressLib.ethAddress()) { msg.sender.transfer(address(this).balance); } else { //simulating exchange pulling funds from the wallet require( IERC20(_asset).transfer( msg.sender, IERC20(_asset).balanceOf(address(this)) ) ); } } }
simulating exchange pulling funds from the wallet
function exchange(address _asset, uint256 _amount) public payable onlyFlashboys { uint256 yield = _amount.mul(FLASHLOAN_LP_YIELD).div( FLASHLOAN_LP_YIELD_BASE ); require(yield <= assetsMaxYield[_asset], "Flashloan is too big"); if (_asset == EthAddressLib.ethAddress()) { require(msg.value == _amount, "The value sent is not enough"); msg.sender.transfer(_amount.add(yield)); require( IERC20(_asset).transferFrom(msg.sender, address(this), _amount) ); require(IERC20(_asset).transfer(msg.sender, _amount.add(yield))); } }
12,648,407
[ 1, 9812, 27967, 7829, 6892, 310, 284, 19156, 628, 326, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7829, 12, 2867, 389, 9406, 16, 2254, 5034, 389, 8949, 13, 203, 3639, 1071, 203, 3639, 8843, 429, 203, 3639, 1338, 11353, 1075, 1900, 203, 565, 288, 203, 3639, 2254, 5034, 2824, 273, 389, 8949, 18, 16411, 12, 42, 16504, 1502, 1258, 67, 14461, 67, 61, 45, 5192, 2934, 2892, 12, 203, 5411, 478, 16504, 1502, 1258, 67, 14461, 67, 61, 45, 5192, 67, 8369, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 23604, 1648, 7176, 2747, 16348, 63, 67, 9406, 6487, 315, 11353, 383, 304, 353, 4885, 5446, 8863, 203, 203, 3639, 309, 261, 67, 9406, 422, 512, 451, 1887, 5664, 18, 546, 1887, 10756, 288, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 389, 8949, 16, 315, 1986, 460, 3271, 353, 486, 7304, 8863, 203, 5411, 1234, 18, 15330, 18, 13866, 24899, 8949, 18, 1289, 12, 23604, 10019, 203, 5411, 2583, 12, 203, 7734, 467, 654, 39, 3462, 24899, 9406, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 13, 203, 5411, 11272, 203, 5411, 2583, 12, 45, 654, 39, 3462, 24899, 9406, 2934, 13866, 12, 3576, 18, 15330, 16, 389, 8949, 18, 1289, 12, 23604, 3719, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x58614A66Dcb3A6D120b8d94bE21140aC6FF8842E/sources/contracts/ERC20_Reputation.sol
Proposal is automatically opened except for TokenOwnership communities since one Orbis master must set the merkle root and quorum supply to use.
Statuses _status = Statuses.Open;
14,270,521
[ 1, 14592, 353, 6635, 10191, 1335, 364, 3155, 5460, 12565, 8391, 1961, 3241, 1245, 2965, 70, 291, 4171, 1297, 444, 326, 30235, 1365, 471, 31854, 14467, 358, 999, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2685, 281, 389, 2327, 273, 2685, 281, 18, 3678, 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 ]
pragma solidity 0.4.24; /** * Interface for defining crowdsale pricing. */ contract PricingStrategy { address public tier; /** Interface declaration. */ function isPricingStrategy() public pure returns (bool) { return true; } /** Self check if all references are correctly set. * * Checks that pricing strategy matches crowdsale parameters. */ function isSane() public pure returns (bool) { return true; } /** * @dev Pricing tells if this is a presale purchase or not. @return False by default, true if a presale purchaser */ function isPresalePurchase() public pure returns (bool) { return false; } /* How many weis one token costs */ function updateRate(uint oneTokenInCents) public; /** * When somebody tries to buy tokens for X eth, calculate how many tokens they get. * * * @param value - What is the value of the transaction send in as wei * @param tokensSold - how much tokens have been sold this far * @param decimals - how many decimal units the token has * @return Amount of tokens the investor receives */ function calculatePrice(uint value, uint tokensSold, uint decimals) public view returns (uint tokenAmount); function oneTokenInWei(uint tokensSold, uint decimals) public view returns (uint); } /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLibExt { function times(uint a, uint b) public pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function divides(uint a, uint b) public pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function minus(uint a, uint b) public pure returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) public pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } 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 view 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; myid; result; proof; // Silence compiler warnings } 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) constant 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(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 &#39;LP\x01&#39; (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 &#39;LP\x01&#39; (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(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; 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(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&#39;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&#39;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&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;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 // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // 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)) } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * Contract which exposes `ethInCents` which is the Ether price in USD cents. * E.g. if 1 Ether is sold at 840.32 USD on the markets, the `ethInCents` will * be `84032`. * * This price is supplied by Oraclize callback, which sets the value. Currently * there is no proof provided for the callback, other then the value and the * corresponding ID which was generated when this contract called Oraclize. * * If this contract runs out of Ether, the callback cycle will interrupt until * the `update` function is called with a transaction which also replenishes the * balance of the contract. */ contract ETHUSD is usingOraclize, Ownable { uint256 public ethInCents; event LogInfo(string description); event LogPriceUpdate(uint256 price); event LogUpdate(address indexed _owner, uint indexed _balance); // Constructor constructor (uint _ethInCents) public payable { ethInCents = _ethInCents; emit LogUpdate(owner, address(this).balance); // Replace the next line with your version: oraclize_setNetwork(1); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); update(); } // Fallback function function() public payable { } function __callback(bytes32 myid, string result, bytes proof) public { require(msg.sender == oraclize_cbAddress()); ethInCents = parseInt(result, 2); emit LogPriceUpdate(ethInCents); update(); } function getBalance() public view returns (uint _balance) { return address(this).balance; } function update() public payable { // Check if we have enough remaining funds if (oraclize_getPrice("URL") > address(this).balance) { emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogInfo("Oraclize query was sent, standing by for the answer.."); // Using XPath to to fetch the right element in the JSON response oraclize_query(7200, "URL", "json(https://api.coinbase.com/v2/prices/ETH-USD/spot).data.amount"); } } function instantUpdate() public payable onlyOwner { // Check if we have enough remaining funds if (oraclize_getPrice("URL") > address(this).balance) { emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogInfo("Oraclize query was sent, standing by for the answer.."); // Using XPath to to fetch the right element in the JSON response oraclize_query("URL", "json(https://api.coinbase.com/v2/prices/ETH-USD/spot).data.amount"); } } function setEthInCents(uint _ethInCents) public onlyOwner { require(_ethInCents > 0); ethInCents = _ethInCents; } function withdrawFunds(address _addr) public onlyOwner { if (msg.sender != owner) revert(); _addr.transfer(address(this).balance); } } /** * Fixed crowdsale pricing - everybody gets the same price. */ contract FlatPricingExt is PricingStrategy, Ownable { using SafeMathLibExt for uint; /* How many weis one token costs */ //uint public oneTokenInWei5; uint public oneTokenInCents; //uint public ethInCents; ETHUSD public ethUsdObj; // Crowdsale rate has been changed event RateChanged(uint oneTokenInCents); constructor(uint _oneTokenInCents, address _ethUSDAddress) public { require(_oneTokenInCents > 0); oneTokenInCents = _oneTokenInCents; ethUsdObj = ETHUSD(_ethUSDAddress); } modifier onlyTier() { if (msg.sender != address(tier)) revert(); _; } function setTier(address _tier) public onlyOwner { assert(_tier != address(0)); assert(tier == address(0)); tier = _tier; } function setEthUSD(address _ethUSDAddress) public onlyOwner { assert(_ethUSDAddress != address(0)); ethUsdObj = ETHUSD(_ethUSDAddress); } function updateRate(uint _oneTokenInCents) public onlyTier { require(_oneTokenInCents > 0); oneTokenInCents = _oneTokenInCents; emit RateChanged(oneTokenInCents); } /** * Calculate the current price for buy in amount. * */ function calculatePrice(uint value, uint tokensSold, uint decimals) public view returns (uint) { uint multiplier = 10 ** decimals; uint oneTokenPriceInWei = oneTokenInWei(tokensSold, decimals); return value.times(multiplier) / oneTokenPriceInWei; } function oneTokenInWei(uint tokensSold, uint decimals) public view returns (uint) { uint multiplier = 10 ** decimals; uint ethInCents = getEthInCents(); uint oneTokenInWei5 = oneTokenInCents.times(multiplier).divides(ethInCents); uint oneTokenInWei1 = oneTokenInWei5.times(60).divides(100); uint oneTokenInWei2 = oneTokenInWei5.times(80).divides(100); uint oneTokenInWei3 = oneTokenInWei5.times(90).divides(100); uint oneTokenInWei4 = oneTokenInWei5.times(95).divides(100); if (tokensSold <= 25000000 * multiplier) return oneTokenInWei1; if (tokensSold > 25000000 * multiplier && tokensSold <= 80000000 * multiplier) return oneTokenInWei2; if (tokensSold > 80000000 * multiplier && tokensSold <= 120000000 * multiplier) return oneTokenInWei3; if (tokensSold > 120000000 * multiplier && tokensSold <= 140000000 * multiplier) return oneTokenInWei4; if (tokensSold > 140000000 * multiplier) return oneTokenInWei5; } function getEthInCents() public view returns (uint) { return ethUsdObj.ethInCents(); } }
* @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./ Memory address of the buffer data Length of existing buffer data Address = buffer address + buffer length + sizeof(buffer length) + len Update buffer length
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 { let bufptr := mload(buf) let buflen := mload(bufptr) let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) mstore(bufptr, add(buflen, len)) } return buf; }
7,916,929
[ 1, 15049, 279, 1160, 358, 326, 679, 434, 326, 1613, 18, 1124, 3128, 309, 9957, 1427, 4102, 9943, 326, 7519, 434, 326, 1613, 18, 225, 1681, 1021, 1613, 358, 714, 358, 18, 225, 501, 1021, 501, 358, 714, 18, 327, 1021, 2282, 1613, 18, 19, 9251, 1758, 434, 326, 1613, 501, 11311, 434, 2062, 1613, 501, 5267, 273, 1613, 1758, 397, 1613, 769, 397, 13726, 12, 4106, 769, 13, 397, 562, 2315, 1613, 769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 714, 1702, 12, 4106, 3778, 1681, 16, 2254, 501, 16, 2254, 562, 13, 2713, 16618, 1135, 12, 4106, 3778, 13, 288, 203, 3639, 309, 261, 1897, 397, 1681, 18, 4385, 18, 2469, 405, 1681, 18, 16017, 13, 288, 203, 5411, 7041, 12, 4385, 16, 943, 12, 4385, 18, 16017, 16, 562, 13, 380, 576, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 3066, 273, 8303, 2826, 562, 300, 404, 31, 203, 3639, 19931, 288, 203, 5411, 2231, 1681, 6723, 519, 312, 945, 12, 4385, 13, 203, 5411, 2231, 1681, 1897, 519, 312, 945, 12, 4385, 6723, 13, 203, 5411, 2231, 1570, 519, 527, 12, 1289, 12, 4385, 6723, 16, 1681, 1897, 3631, 562, 13, 203, 5411, 312, 2233, 12, 10488, 16, 578, 12, 464, 12, 81, 945, 12, 10488, 3631, 486, 12, 4455, 13, 3631, 501, 3719, 203, 5411, 312, 2233, 12, 4385, 6723, 16, 527, 12, 4385, 1897, 16, 562, 3719, 203, 3639, 289, 203, 3639, 327, 1681, 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 ]
./partial_match/42/0xd2c4E0962253a2426Cc1Db8bA6E86De5c858B1d4/sources/FoggyBog.sol
lava uniswap-eth v2 pair
address private _lavaUniV2Pair;
3,395,306
[ 1, 80, 1629, 640, 291, 91, 438, 17, 546, 331, 22, 3082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 3238, 389, 80, 1629, 984, 77, 58, 22, 4154, 31, 1850, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x1F033Cb8A2Df08a147BC512723fd0da3FEc5cCA7/sources/autopay/contracts/Autopay.sol
index plus one of dataFeedID in feedsWithFunding array (0 if not in array)
uint256 feedsWithFundingIndex;
4,950,759
[ 1, 1615, 8737, 1245, 434, 501, 8141, 734, 316, 27684, 1190, 42, 14351, 526, 261, 20, 309, 486, 316, 526, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 27684, 1190, 42, 14351, 1016, 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 ]
pragma solidity ^0.5.2; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ enum AirlineStatus {Unregistered, WaitingConsensus, Registered, Active} // Airline status struct AirlineInfo { string name; AirlineStatus status; address referrer; } struct PassengerInfo { string name; mapping(string => uint) insuranceBought; // Store insurance bought by this passenger } struct Flight { bool isRegistered; uint8 statusCode; // status code is defined in App Contract in case we want to modify it uint256 updatedTimestamp; address airline; bool active; address[] addressList; } address private contractOwner; // Account used to deploy contract mapping(address => bool) private allowedContracts; // Store allowed contract to call this contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => AirlineInfo) private airlines; // Store airlines whether they are registered/have paid the fee uint numberOfRegisteredAirline = 1; // Store how many airlines are currently registered, first airline registerd during deployment mapping(string => Flight) private flights; // Store passenger's wallet for the given flight insurance mapping(address => PassengerInfo) private passengers; // Store detail of passenger who bought insurance mapping(address => uint) private payouts; // Payouts amount for passenger /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Event that tells that a new airline is added to the mapping */ event NewAirlineAdded(string _airlineName); /** * @dev Constructor * The deploying account becomes contractOwner First airline will be registered */ constructor(address _firstAirlineAddress, string memory _firstAirlineName) public { contractOwner = msg.sender; // register first airline when contract deployed AirlineInfo memory info; info.name = _firstAirlineName; info.status = AirlineStatus.Registered; airlines[_firstAirlineAddress] = info; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the origin to be a registered airline */ modifier requireRegisteredContract { require(allowedContracts[msg.sender] == true, "Need a registered contract"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /** * @dev Add allowed contracts to call this contract */ function registerContract(address _address) external requireContractOwner { allowedContracts[_address] = true; } /** * @dev Deregister allowed contracts to call this contract */ function deRegisterContract(address _address) external requireContractOwner { allowedContracts[_address] = false; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function getNumberOfRegisteredAirline() public view returns(uint) { return numberOfRegisteredAirline; } /** * @dev Add an airline to the registration queue with WaitingConsensus status * Can only be called from FlightSuretyApp contract * */ function registerAirline(address _airlineAddress, string calldata _airlineName) external requireRegisteredContract requireIsOperational { AirlineInfo memory info; info.name = _airlineName; info.status = AirlineStatus.WaitingConsensus; airlines[_airlineAddress] = info; emit NewAirlineAdded(_airlineName); } /** * @dev Update status of an airline to the registered status * Can only be called from FlightSuretyApp contract * */ function updateAirlineStatusToRegistered(address _airlineAddress) external requireRegisteredContract requireIsOperational { airlines[_airlineAddress].status = AirlineStatus.Registered; numberOfRegisteredAirline += 1; } /** * @dev Airline has paid ante, activate */ function payAnte(address _airlineAddress) external payable requireRegisteredContract requireIsOperational { require(airlines[_airlineAddress].status == AirlineStatus.Registered, "Airline is not yet registered"); // change status of the airline to active airlines[_airlineAddress].status = AirlineStatus.Active; } /** * @dev get the status of an airline address * */ function getAirlineStatus(address _airlineAddress) external view returns (uint _status) { _status = uint(airlines[_airlineAddress].status); } /** * @dev check if airline address is listed * AirlineStatus.WaitingConsensus or AirlineStatus.Registered or AirlineStatus.Active */ function isAirlineListed(address _airlineAddress) external view returns (bool) { if (airlines[_airlineAddress].status != AirlineStatus.Unregistered) { return true; } else { return false; } } /** * @dev check if airline address is registered * AirlineStatus.Registered */ function isAirlineRegistered(address _airlineAddress) external view returns (bool) { if (airlines[_airlineAddress].status == AirlineStatus.Registered) { return true; } else { return false; } } /** * @dev check if airline address is active * AirlineStatus.Active */ function isAirlineActive(address _airlineAddress) external view returns (bool) { if (airlines[_airlineAddress].status == AirlineStatus.Active) { return true; } else { return false; } } /** * @dev register a flight and list of insurances available for buying * */ function registerFlight(string calldata _flightNumber, address _airline, uint256 _timestamp) external requireRegisteredContract requireIsOperational { require(flights[_flightNumber].isRegistered == false, "Flight is already registered"); flights[_flightNumber].active = true; flights[_flightNumber].isRegistered = true; flights[_flightNumber].airline = _airline; flights[_flightNumber].updatedTimestamp = _timestamp; } /** * @dev get flight info * */ function getFlight(string memory _flightNumber) public view returns(bool _active, bool _isRegistered, address _airline, uint256 _timestamp) { _active = flights[_flightNumber].active; _isRegistered = flights[_flightNumber].isRegistered; _airline = flights[_flightNumber].airline; _timestamp = flights[_flightNumber].updatedTimestamp; } /** * @dev Buy insurance for a flight * */ function buy(string calldata _flightNumber, address _buyerAddress) external payable requireIsOperational { require (flights[_flightNumber].active == true, "Flight is not currently active"); require (msg.value > 0, "Amount must be greater than zero"); require (passengers[_buyerAddress].insuranceBought[_flightNumber] == 0, "You have bought an insurance for this flight"); // add into flight number list of passenger who bought insurance flights[_flightNumber].addressList.push(_buyerAddress); // update this passenger insurance bought passengers[_buyerAddress].insuranceBought[_flightNumber] = msg.value; } /** * @dev Check insurance detail * */ function checkInsurance(string memory _flightNumber, address _passengerAddress) public view returns(uint256 _amount) { return passengers[_passengerAddress].insuranceBought[_flightNumber]; } /** * @dev Check payouts * */ function checkPayouts() public view returns(uint256 _amount) { return payouts[msg.sender]; } /** * @dev Credits payouts to insuree * WARNING there is a for loop in this function */ function creditInsurees(string calldata _flightNumber, uint16 _payoutRatio) external requireRegisteredContract requireIsOperational { address[] memory addresses = flights[_flightNumber].addressList; flights[_flightNumber].active = false; for (uint i = 0; i < addresses.length; i++) { uint insuranceAmount = passengers[addresses[i]].insuranceBought[_flightNumber]; // empty out the insurance for this passenger passengers[addresses[i]].insuranceBought[_flightNumber] = 0; payouts[addresses[i]] += insuranceAmount.mul(_payoutRatio).div(10); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay() external requireIsOperational { require(payouts[msg.sender] > 0, "Balance is zero"); uint amount = payouts[msg.sender]; payouts[msg.sender] = 0; msg.sender.transfer(amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund() public payable { } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
* @dev Update status of an airline to the registered status Can only be called from FlightSuretyApp contract/
function updateAirlineStatusToRegistered(address _airlineAddress) external requireRegisteredContract requireIsOperational { airlines[_airlineAddress].status = AirlineStatus.Registered; numberOfRegisteredAirline += 1; }
13,043,171
[ 1, 1891, 1267, 434, 392, 23350, 1369, 358, 326, 4104, 1267, 1377, 4480, 1338, 506, 2566, 628, 3857, 750, 55, 594, 4098, 3371, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 29752, 1369, 1482, 774, 10868, 12, 2867, 389, 1826, 1369, 1887, 13, 3903, 2583, 10868, 8924, 7010, 565, 2583, 2520, 2988, 287, 288, 203, 3639, 23350, 3548, 63, 67, 1826, 1369, 1887, 8009, 2327, 273, 432, 481, 1369, 1482, 18, 10868, 31, 203, 3639, 7922, 10868, 29752, 1369, 1011, 404, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x61bd3674215ac3f8C6F3499AF0169f37AfeCf4e3/sources/browser/exchange.sol
* @dev Modifier to make a function callable only when the contract is paused./
modifier whenPaused() { require(contractPaused); _; }
8,189,571
[ 1, 9829, 358, 1221, 279, 445, 4140, 1338, 1347, 326, 6835, 353, 17781, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1347, 28590, 1435, 288, 203, 3639, 2583, 12, 16351, 28590, 1769, 203, 3639, 389, 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 ]
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/src/libraries/Helpers.sol
Assert that the total amount is strictly greater than the sum of the protocol fee amount and the broker fee amount.
assert(totalAmount > amounts.protocolFee + amounts.brokerFee);
9,308,299
[ 1, 8213, 716, 326, 2078, 3844, 353, 23457, 6802, 2353, 326, 2142, 434, 326, 1771, 14036, 3844, 471, 326, 8625, 14036, 3844, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 1815, 12, 4963, 6275, 405, 30980, 18, 8373, 14667, 397, 30980, 18, 21722, 14667, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xEF4f15Bc6491d046C18f68aB5Dc71BF62B087e22/sources/PynthUtil.sol
Inheritance https:docs.pynthetix.io/contracts/source/contracts/synthutil
contract PynthUtil { IAddressResolver public addressResolverProxy; bytes32 internal constant CONTRACT_PYNTHETIX = "Pynthetix"; bytes32 internal constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 internal constant SUSD = "pUSD"; function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); function freezeRate(bytes32 currencyKey) external; } } } constructor(address resolver) public { addressResolverProxy = IAddressResolver(resolver); } function _pynthetix() internal view returns (IPynthetix) { return IPynthetix(addressResolverProxy.requireAndGetAddress(CONTRACT_PYNTHETIX, "Missing Pynthetix address")); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(addressResolverProxy.requireAndGetAddress(CONTRACT_EXRATES, "Missing ExchangeRates address")); } function totalPynthsInKey(address account, bytes32 currencyKey) external view returns (uint total) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint numPynths = pynthetix.availablePynthCount(); for (uint i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); total += exchangeRates.effectiveValue( synth.currencyKey(), IERC20(address(synth)).balanceOf(account), currencyKey ); } return total; } function totalPynthsInKey(address account, bytes32 currencyKey) external view returns (uint total) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint numPynths = pynthetix.availablePynthCount(); for (uint i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); total += exchangeRates.effectiveValue( synth.currencyKey(), IERC20(address(synth)).balanceOf(account), currencyKey ); } return total; } function pynthsBalances(address account) external view returns ( bytes32[] memory, uint[] memory, uint[] memory ) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint numPynths = pynthetix.availablePynthCount(); bytes32[] memory currencyKeys = new bytes32[](numPynths); uint[] memory balances = new uint[](numPynths); uint[] memory pUSDBalances = new uint[](numPynths); for (uint i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); currencyKeys[i] = synth.currencyKey(); balances[i] = IERC20(address(synth)).balanceOf(account); pUSDBalances[i] = exchangeRates.effectiveValue(currencyKeys[i], balances[i], SUSD); } return (currencyKeys, balances, pUSDBalances); } function pynthsBalances(address account) external view returns ( bytes32[] memory, uint[] memory, uint[] memory ) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint numPynths = pynthetix.availablePynthCount(); bytes32[] memory currencyKeys = new bytes32[](numPynths); uint[] memory balances = new uint[](numPynths); uint[] memory pUSDBalances = new uint[](numPynths); for (uint i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); currencyKeys[i] = synth.currencyKey(); balances[i] = IERC20(address(synth)).balanceOf(account); pUSDBalances[i] = exchangeRates.effectiveValue(currencyKeys[i], balances[i], SUSD); } return (currencyKeys, balances, pUSDBalances); } function frozenPynths() external view returns (bytes32[] memory) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint numPynths = pynthetix.availablePynthCount(); bytes32[] memory frozenPynthsKeys = new bytes32[](numPynths); for (uint i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); if (exchangeRates.rateIsFrozen(synth.currencyKey())) { frozenPynthsKeys[i] = synth.currencyKey(); } } return frozenPynthsKeys; } function frozenPynths() external view returns (bytes32[] memory) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint numPynths = pynthetix.availablePynthCount(); bytes32[] memory frozenPynthsKeys = new bytes32[](numPynths); for (uint i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); if (exchangeRates.rateIsFrozen(synth.currencyKey())) { frozenPynthsKeys[i] = synth.currencyKey(); } } return frozenPynthsKeys; } function frozenPynths() external view returns (bytes32[] memory) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint numPynths = pynthetix.availablePynthCount(); bytes32[] memory frozenPynthsKeys = new bytes32[](numPynths); for (uint i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); if (exchangeRates.rateIsFrozen(synth.currencyKey())) { frozenPynthsKeys[i] = synth.currencyKey(); } } return frozenPynthsKeys; } function pynthsRates() external view returns (bytes32[] memory, uint[] memory) { bytes32[] memory currencyKeys = _pynthetix().availableCurrencyKeys(); return (currencyKeys, _exchangeRates().ratesForCurrencies(currencyKeys)); } function pynthsTotalSupplies() external view returns ( bytes32[] memory, uint256[] memory, uint256[] memory ) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint256 numPynths = pynthetix.availablePynthCount(); bytes32[] memory currencyKeys = new bytes32[](numPynths); uint256[] memory balances = new uint256[](numPynths); uint256[] memory pUSDBalances = new uint256[](numPynths); for (uint256 i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); currencyKeys[i] = synth.currencyKey(); balances[i] = IERC20(address(synth)).totalSupply(); pUSDBalances[i] = exchangeRates.effectiveValue(currencyKeys[i], balances[i], SUSD); } return (currencyKeys, balances, pUSDBalances); } function pynthsTotalSupplies() external view returns ( bytes32[] memory, uint256[] memory, uint256[] memory ) { IPynthetix pynthetix = _pynthetix(); IExchangeRates exchangeRates = _exchangeRates(); uint256 numPynths = pynthetix.availablePynthCount(); bytes32[] memory currencyKeys = new bytes32[](numPynths); uint256[] memory balances = new uint256[](numPynths); uint256[] memory pUSDBalances = new uint256[](numPynths); for (uint256 i = 0; i < numPynths; i++) { IPynth synth = pynthetix.availablePynths(i); currencyKeys[i] = synth.currencyKey(); balances[i] = IERC20(address(synth)).totalSupply(); pUSDBalances[i] = exchangeRates.effectiveValue(currencyKeys[i], balances[i], SUSD); } return (currencyKeys, balances, pUSDBalances); } }
3,492,479
[ 1, 28255, 2333, 30, 8532, 18, 84, 878, 451, 278, 697, 18, 1594, 19, 16351, 87, 19, 3168, 19, 16351, 87, 19, 11982, 451, 1367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 453, 878, 451, 1304, 288, 203, 565, 467, 1887, 4301, 1071, 1758, 4301, 3886, 31, 203, 203, 565, 1731, 1578, 2713, 5381, 8020, 2849, 1268, 67, 16235, 1784, 44, 1584, 12507, 273, 315, 52, 878, 451, 278, 697, 14432, 203, 565, 1731, 1578, 2713, 5381, 8020, 2849, 1268, 67, 2294, 24062, 55, 273, 315, 11688, 20836, 14432, 203, 565, 1731, 1578, 2713, 5381, 348, 3378, 40, 273, 315, 84, 3378, 40, 14432, 203, 203, 565, 445, 4377, 3062, 12, 3890, 1578, 5462, 653, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 20762, 6210, 5094, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 1281, 4727, 2520, 1941, 12, 3890, 1578, 8526, 745, 892, 5462, 2396, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 848, 9194, 8489, 4727, 12, 3890, 1578, 5462, 653, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 783, 11066, 1290, 4727, 12, 3890, 1578, 5462, 653, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 19239, 7736, 17711, 12, 2867, 20762, 13, 3903, 1476, 1135, 261, 3890, 1578, 8526, 3778, 1769, 203, 203, 565, 445, 11448, 620, 12, 203, 3639, 1731, 1578, 1084, 7623, 653, 16, 203, 3639, 2254, 1084, 6275, 16, 203, 3639, 1731, 1578, 2929, 7623, 653, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 460, 1769, 203, 203, 565, 445, 11448, 620, 1876, 20836, 12, 203, 3639, 1731, 1578, 1084, 7623, 653, 16, 203, 3639, 2254, 1084, 6275, 16, 203, 3639, 1731, 1578, 2929, 2 ]