file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/42/0xB6697509643FDE9033742458DE9dBF5639f5af9c/sources/coin_in_sc.sol
Use the below address for Kovan BELOW HERE I DEFINE THE KOVAN BASE TOKEN ADDRESSES BELOW HERE I DEFINE THE MAINNET BASE TOKEN ADDRESSES address private constant WETH_sc = ; address private constant USDC_sc = ; address private constant USDT_sc = ; Use the below for MAINNETaddress public immutable owner = 0x722A8DE5FCBe9838d9F2cC52b4610A8eDcBD36Ba; Need this constructor to set the implementation
contract CoinStorageTest { address public immutable owner; address private constant WETH_sc = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; ChiToken constant public chi = ChiToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); IERC20 constant public WETH_token = IERC20(0xd0A1E359811322d97991E03f863a0C30C2cF029C); using SafeMath for uint; constructor() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chi.freeUpTo((gasSpent + 14154) / 41947); } modifier discountCHIWallet { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } modifier isWETHInPair(address _pair){ address token0 = IUniswapV2Pair(_pair).token0(); address token1 = IUniswapV2Pair(_pair).token1(); require((token0 == WETH_sc) || (token1 == WETH_sc)); _; } function transferAllTokensToWallet(address token_) external onlyOwner{ IERC20 token = IERC20(token_); uint coinPositionAtContractExecution = token.balanceOf(address(this)); token.transfer(owner, coinPositionAtContractExecution); } function withdrawNoModifier(address token_ ) external { require(msg.sender == owner); IERC20 token = IERC20(token_); uint coinPositionAtContractExecution = token.balanceOf(address(this)); token.transfer(owner, coinPositionAtContractExecution); } function transferListAllTokensToWallet(address [] memory addresses_) external onlyOwner{ uint arrayLength = addresses_.length; for (uint256 i = 0; i < arrayLength; i++){ IERC20 token = IERC20(addresses_[i]); uint coinPositionAtContractExecution = token.balanceOf(address(this)); token.transfer(owner, coinPositionAtContractExecution); } } function transferListAllTokensToWallet(address [] memory addresses_) external onlyOwner{ uint arrayLength = addresses_.length; for (uint256 i = 0; i < arrayLength; i++){ IERC20 token = IERC20(addresses_[i]); uint coinPositionAtContractExecution = token.balanceOf(address(this)); token.transfer(owner, coinPositionAtContractExecution); } } function transferTokensToWallet(address token_, uint256 amount_) external onlyOwner{ IERC20 token = IERC20(token_); token.transfer(owner, amount_); } function swap_1( uint256 _amountIn, uint256 _amountOutMin, address _inputToken, address _outputToken, address _pair ) external payable onlyOwner { uint[] memory amounts = _getAmountsOut(_pair, _amountIn, _inputToken, _outputToken); require(amounts[1] >= _amountOutMin, 'swapExactTokensForTokens: amounts[1] < amountOutMin'); TransferHelper.safeTransfer(_inputToken, _pair, amounts[0]); _swap(amounts, _inputToken, _outputToken, address(this), _pair); } function swap_2( uint256 _amountIn, uint256 _amountOutMin, address _inputToken, address _outputToken, address _pair ) external payable onlyOwner { uint256 calcAmountOutMin = _getAmountsOutTest(_pair, _amountIn, _inputToken, _outputToken); require(calcAmountOutMin >= _amountOutMin, 'swapExactTokensForTokens: amounts[1] < amountOutMin'); IERC20 token = IERC20(_inputToken); token.transfer(_pair, _amountIn); _swapTest(calcAmountOutMin, _inputToken, _outputToken, address(this), _pair); } function swap_2_chi( uint256 _amountIn, uint256 _amountOutMin, address _inputToken, address _outputToken, address _pair ) external payable onlyOwner discountCHI{ uint256 calcAmountOutMin = _getAmountsOutTest(_pair, _amountIn, _inputToken, _outputToken); require(calcAmountOutMin >= _amountOutMin, 'swapExactTokensForTokens: amounts[1] < amountOutMin'); IERC20 token = IERC20(_inputToken); token.transfer(_pair, _amountIn); _swapTest(calcAmountOutMin, _inputToken, _outputToken, address(this), _pair); } function swap_reduced_inputs_WETH_1( uint256 _amountIn, uint256 _amountOutMin, address _pair ) external payable onlyOwner isWETHInPair(_pair){ uint256 calcAmountOutMin = _getAmountsOutWETH_NEW(_pair, _amountIn); require(calcAmountOutMin >= _amountOutMin, 'swapExactTokensForTokens: amounts[1] < amountOutMin'); WETH_token.transfer(_pair, _amountIn); _swapWETH_NEW(calcAmountOutMin, address(this), _pair); } function swap_reduced_inputs_WETH_2( uint256 _amountIn, uint256 _amountOutMin, address _pair ) external payable onlyOwner{ uint256 calcAmountOutMin = _getAmountsOutWETH_NEW(_pair, _amountIn); require(calcAmountOutMin >= _amountOutMin, 'swapExactTokensForTokens: amounts[1] < amountOutMin'); WETH_token.transfer(_pair, _amountIn); _swapWETH_NEW(calcAmountOutMin, address(this), _pair); } function swap_reduced_inputs_WETH_3( uint256 _amountIn, uint256 _amountOutMin, address _pair ) external payable onlyOwner isWETHInPair(_pair) discountCHI{ uint256 calcAmountOutMin = _getAmountsOutWETH_NEW(_pair, _amountIn); require(calcAmountOutMin >= _amountOutMin, 'swapExactTokensForTokens: amounts[1] < amountOutMin'); WETH_token.transfer(_pair, _amountIn); _swapWETH_NEW(calcAmountOutMin, address(this), _pair); } function _getAmountsOutWETH_NEW(address pair, uint amountIn) internal view returns (uint256 calcAmountOutMin) { (uint reserveIn, uint reserveOut) = _computeReservesWETH_NEW(pair); calcAmountOutMin = _computeAmountOut(amountIn, reserveIn, reserveOut); } function _computeReservesWETH_NEW(address pair) internal view returns (uint reserveA, uint reserveB) { address token0 = IUniswapV2Pair(pair).token0(); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = WETH_sc == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function _swapWETH_NEW(uint256 calcAmountOutMin, address to, address pair) internal { address token0 = IUniswapV2Pair(pair).token0(); (uint amount0Out, uint amount1Out) = WETH_sc == token0 ? (uint(0), calcAmountOutMin) : (calcAmountOutMin, uint(0)); IUniswapV2Pair(pair).swap(amount0Out, amount1Out, to, new bytes(0)); } function _swap(uint[] memory amounts, address input, address output, address to, address pair) internal { (address token0,) = _sortTokens(input, output); uint amountOut = amounts[1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); IUniswapV2Pair(pair).swap(amount0Out, amount1Out, to, new bytes(0)); } function _swapTest(uint256 calcAmountOutMin, address input, address output, address to, address pair) internal { (address token0,) = _sortTokens(input, output); (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), calcAmountOutMin) : (calcAmountOutMin, uint(0)); IUniswapV2Pair(pair).swap(amount0Out, amount1Out, to, new bytes(0)); } function _computeAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function _getAmountsOut(address pair, uint amountIn, address inputToken, address outputToken) internal view returns (uint[] memory amounts) { amounts = new uint[](2); amounts[0] = amountIn; (uint reserveIn, uint reserveOut) = _computeReserves(pair, inputToken, outputToken); amounts[1] = _computeAmountOut(amounts[0], reserveIn, reserveOut); } function _getAmountsOutTest(address pair, uint amountIn, address inputToken, address outputToken) internal view returns (uint256 calcAmountOutMin) { (uint reserveIn, uint reserveOut) = _computeReserves(pair, inputToken, outputToken); calcAmountOutMin = _computeAmountOut(amountIn, reserveIn, reserveOut); } function _sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); } function _computeReserves(address pair, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = _sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } }
16,223,004
[ 1, 3727, 326, 5712, 1758, 364, 1475, 1527, 304, 9722, 4130, 670, 29340, 467, 25957, 3740, 12786, 1475, 51, 58, 1258, 10250, 14275, 11689, 7031, 1090, 55, 9722, 4130, 670, 29340, 467, 25957, 3740, 12786, 22299, 14843, 10250, 14275, 11689, 7031, 1090, 55, 1758, 3238, 5381, 678, 1584, 44, 67, 1017, 273, 274, 1758, 3238, 5381, 11836, 5528, 67, 1017, 273, 274, 1758, 3238, 5381, 11836, 9081, 67, 1017, 273, 274, 2672, 326, 5712, 364, 22299, 14843, 2867, 1071, 11732, 3410, 273, 374, 92, 27, 3787, 37, 28, 1639, 25, 4488, 1919, 10689, 7414, 72, 29, 42, 22, 71, 39, 9401, 70, 8749, 2163, 37, 28, 73, 40, 71, 18096, 5718, 38, 69, 31, 12324, 333, 3885, 358, 444, 326, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 28932, 3245, 4709, 288, 203, 203, 565, 1758, 1071, 11732, 3410, 31, 203, 377, 203, 565, 1758, 3238, 5381, 678, 1584, 44, 67, 1017, 273, 374, 7669, 20, 37, 21, 41, 4763, 10689, 2499, 1578, 22, 72, 10580, 2733, 21, 41, 4630, 74, 28, 4449, 69, 20, 39, 5082, 39, 22, 71, 42, 3103, 29, 39, 31, 203, 203, 377, 203, 377, 203, 565, 1680, 77, 1345, 5381, 1071, 17198, 273, 1680, 77, 1345, 12, 20, 92, 12648, 2787, 7616, 8749, 71, 20, 73, 29, 42, 8942, 42, 24, 758, 73, 4848, 27, 70, 20, 73, 42, 21, 29534, 21, 71, 1769, 203, 565, 467, 654, 39, 3462, 5381, 1071, 678, 1584, 44, 67, 2316, 273, 467, 654, 39, 3462, 12, 20, 7669, 20, 37, 21, 41, 4763, 10689, 2499, 1578, 22, 72, 10580, 2733, 21, 41, 4630, 74, 28, 4449, 69, 20, 39, 5082, 39, 22, 71, 42, 3103, 29, 39, 1769, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 3885, 1435, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 377, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 9606, 12137, 1792, 45, 288, 203, 565, 2254, 5034, 16189, 1685, 273, 16189, 4482, 5621, 203, 565, 389, 31, 203, 565, 2254, 5034, 16189, 3389, 319, 273, 9035, 3784, 397, 16189, 1685, 300, 16189, 4482, 1435, 397, 2872, 380, 1234, 18, 892, 18, 2 ]
./partial_match/1/0x8d0FcB0251081873ee725e184d6e0618107db196/sources/Baby$DIE.sol
update launch tax ratios
function updateLaunchTransferTax( uint8 newLaunchTransferTax ) external onlyOwner { require(launchTransferTax > 0, "Launch Transfer Tax has been removed and cannot be re-enabled"); launchTransferTax = newLaunchTransferTax; }
15,938,039
[ 1, 2725, 8037, 5320, 25706, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 9569, 5912, 7731, 12, 203, 3639, 2254, 28, 394, 9569, 5912, 7731, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 20738, 5912, 7731, 405, 374, 16, 315, 9569, 12279, 18240, 711, 2118, 3723, 471, 2780, 506, 283, 17, 5745, 8863, 203, 3639, 8037, 5912, 7731, 273, 394, 9569, 5912, 7731, 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 ]
pragma solidity >=0.4.0 <0.6.0; import "./RelayHubApi.sol"; import "./RelayRecipient.sol"; import "./RLPReader.sol"; contract RelayHub is RelayHubApi { string public hello = "hello"; // Anyone can call certain functions in this singleton and trigger relay processes. uint constant timeout = 5 days; // XXX TBD uint constant minimum_stake = 1; // XXX TBD uint constant minimum_unstake_delay = 0; // XXX TBD uint constant minimum_relay_balance = 0.5 ether; // XXX TBD - can't register/refresh below this amount. uint constant low_ether = 1 ether; // XXX TBD - relay still works, but owner should be notified to fund the relay soon. uint constant public gas_reserve = 99999; // XXX TBD - calculate how much reserve we actually need, to complete the post-call part of relay(). uint constant public gas_overhead = 47382; // the total gas overhead of relay(), before the first gasleft() and after the last gasleft(). Assume that relay has non-zero balance (costs 15'000 more otherwise). mapping (address => uint) public nonces; // Nonces of senders, since their ether address nonce may never change. struct Relay { uint timestamp; uint transaction_fee; } mapping (address => Relay) public relays; struct Stake { uint stake; // Size of the stake uint unstake_delay; // How long between removal and unstaking uint unstake_time; // When is the stake released. Non-zero means that the relay has been removed and is waiting for unstake. address owner; bool removed; } mapping (address => Stake) public stakes; mapping (address => uint) public balances; function validate_stake(address relay) private view { require(stakes[relay].stake >= minimum_stake,"stake lower than minimum"); // Has enough stake? require(stakes[relay].unstake_delay >= minimum_unstake_delay,"delay lower than minimum"); // Locked for enough time? } modifier lock_stake() { validate_stake(msg.sender); require(msg.sender.balance >= minimum_relay_balance,"balance lower than minimum"); stakes[msg.sender].unstake_time = 0; // Activate the lock _; } function safe_add(uint a, uint b) internal pure returns (uint) { uint256 c = a + b; assert(c >= a); return c; } function safe_sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function get_nonce(address from) view external returns (uint) { return nonces[from]; } /** * deposit ether for a contract. * This ether will be used to repay relay calls into this contract. * Contract owner should monitor the balance of his contract, and make sure * to deposit more, otherwise the contract won't be able to receive relayed calls. * Unused deposited can be withdrawn with `withdraw()` */ function depositFor(address target) public payable { balances[target] += msg.value; require (balances[target] >= msg.value); emit Deposited(target, msg.value); } function deposit() public payable { depositFor(msg.sender); } /** * withdraw funds. * caller is either a relay owner, withdrawing collected transaction fees. * or a RelayRecipient contract, withdrawing its deposit. * note that while everyone can `depositFor()` a contract, only * the contract itself can withdraw its funds. */ function withdraw(uint amount) public { require(balances[msg.sender] >= amount, "insufficient funds"); balances[msg.sender] -= amount; msg.sender.transfer(amount); emit Withdrawn(msg.sender, amount); } //check the deposit balance of a contract. function balanceOf(address target) external view returns (uint256) { return balances[target]; } function stakeOf(address relay) external view returns (uint256) { return stakes[relay].stake; } function ownerOf(address relay) external view returns (address) { return stakes[relay].owner; } function stake(address relay, uint unstake_delay) external payable { // Create or increase the stake and unstake_delay require(stakes[relay].owner == address(0) || stakes[relay].owner == msg.sender, "not owner"); stakes[relay].owner = msg.sender; stakes[relay].stake += msg.value; // Make sure that the relay doesn't decrease his delay if already registered require(unstake_delay >= stakes[relay].unstake_delay, "unstake_delay cannot be decreased"); stakes[relay].unstake_delay = unstake_delay; validate_stake(relay); emit Staked(relay, msg.value); } function can_unstake(address relay) public view returns(bool) { // Only owner can unstake if (stakes[relay].owner != msg.sender) { return false; } if (relays[relay].timestamp != 0 || stakes[relay].unstake_time == 0) // Relay still registered so unstake time hasn't been set return false; return stakes[relay].unstake_time <= now; // Finished the unstaking delay period? } modifier unstake_allowed(address relay) { require(can_unstake(relay)); _; } function unstake(address relay) public unstake_allowed(relay) { uint amount = stakes[relay].stake; msg.sender.transfer(stakes[relay].stake); delete stakes[relay]; emit Unstaked(relay, amount); } function register_relay(uint transaction_fee, string memory url, address optional_relay_removal) public lock_stake { // Anyone with a stake can register a relay. Apps choose relays by their transaction fee, stake size and unstake delay, // optionally crossed against a blacklist. Apps verify the relay's action in realtime. Stake storage relay_stake = stakes[msg.sender]; // Penalized relay cannot reregister require(!relay_stake.removed, "Penalized relay cannot reregister"); relays[msg.sender] = Relay(now, transaction_fee); emit RelayAdded(msg.sender, relay_stake.owner, transaction_fee, relay_stake.stake, relay_stake.unstake_delay, url); // @optional_relay_removal is unrelated to registration, but incentivizes relays to help purging stale relays from the list. // Providing a stale relay will cause its removal, and offset the gas price of registration. if (optional_relay_removal != address(0)) remove_stale_relay(optional_relay_removal); } function remove_relay_internal(address relay) internal { delete relays[relay]; stakes[relay].unstake_time = stakes[relay].unstake_delay + now; // Start the unstake counter stakes[relay].removed = true; emit RelayRemoved(relay, stakes[relay].unstake_time); } function remove_stale_relay(address relay) public { // Trustless, assumed to be called by anyone willing to pay for the gas. Verifies staleness. Normally called by relays to keep the list current. require(relays[relay].timestamp != 0, "not a relay"); // Relay exists? require(relays[relay].timestamp + timeout < now, "not stale"); // Did relay send a keeplive recently? // Anyone can remove a stale relay. remove_relay_internal(relay); } modifier relay_owner(address relay) { require(stakes[relay].owner == msg.sender, "not owner"); _; } function remove_relay_by_owner(address relay) public relay_owner(relay) { // The relay's owner can remove it at any time, to start the unstake countdown. remove_relay_internal(relay); } function check_sig(address signer, bytes32 hash, bytes memory sig) pure internal returns (bool) { // Check if @v,@r,@s are a valid signature of @signer for @hash return signer == ecrecover(hash, uint8(sig[0]), bytesToBytes32(sig,1), bytesToBytes32(sig,33)); } //check if the Hub can accept this relayed operation. // it validates the caller's signature and nonce, and then delegates to the destination's accept_relayed_call // for contract-specific checks. // returns "0" if the relay is valid. other values represent errors. // values 1..10 are reserved for can_relay. other values can be used by accept_relayed_call of target contracts. function can_relay(address relay, address from, RelayRecipient to, bytes memory transaction, uint transaction_fee, uint gas_price, uint gas_limit, uint nonce, bytes memory sig) public view returns(uint32) { bytes memory packed = abi.encodePacked("rlx:", from, to, transaction, transaction_fee, gas_price, gas_limit, nonce, address(this)); bytes32 hashed_message = keccak256(abi.encodePacked(packed, relay)); bytes32 signed_message = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashed_message)); if (!check_sig(from, signed_message, sig)) // Verify the sender's signature on the transaction return 1; // @from hasn't signed the transaction properly if (nonces[from] != nonce) return 2; // Not a current transaction. May be a replay attempt. // XXX check @to's balance, roughly estimate if it has enough balance to pay the transaction fee. It's the relay's responsibility to verify, but check here too. return to.accept_relayed_call(relay, from, transaction, gas_price, transaction_fee); // Check to.accept_relayed_call, see if it agrees to accept the charges. } /** * relay a transaction. * @param from the client originating the request. * @param to the target RelayRecipient contract. * @param encoded_function the function call to relay. * @param transaction_fee fee (%) the relay takes over actual gas cost. * @param gas_price gas price the client is willing to pay * @param gas_limit limit the client want to put on its transaction * @param transaction_fee fee (%) the relay takes over actual gas cost. * @param nonce sender's nonce (in nonces[]) * @param sig client's signature over all params */ function relay(address from, address to, bytes memory encoded_function, uint transaction_fee, uint gas_price, uint gas_limit, uint nonce, bytes memory sig) public { uint initial_gas = gasleft(); require(relays[msg.sender].timestamp > 0, "Unknown relay"); // Must be from a known relay require(gas_price <= tx.gasprice, "Invalid gas price"); // Relay must use the gas price set by the signer relays[msg.sender].timestamp = now; require(0 == can_relay(msg.sender, from, RelayRecipient(to), encoded_function, transaction_fee, gas_price, gas_limit, nonce, sig), "can_relay failed"); // ensure that the last bytes of @transaction are the @from address. // Recipient will trust this reported sender when msg.sender is the known RelayHub. bytes memory transaction = abi.encodePacked(encoded_function,from); // gas_reserve must be high enough to complete relay()'s post-call execution. require(safe_sub(initial_gas,gas_limit) >= gas_reserve, "Not enough gasleft()"); bool success = executeCallWithGas(gas_limit, to, 0, transaction); // transaction must end with @from at this point nonces[from]++; RelayRecipient(to).post_relayed_call(msg.sender, from, encoded_function, success, (gas_overhead+initial_gas-gasleft()), transaction_fee ); // Relay transaction_fee is in %. E.g. if transaction_fee=40, payment will be 1.4*used_gas. uint charge = (gas_overhead+initial_gas-gasleft())*gas_price*(100+transaction_fee)/100; emit TransactionRelayed(msg.sender, from, to, keccak256(encoded_function), success, charge); require(balances[to] >= charge, "insufficient funds"); balances[to] -= charge; balances[stakes[msg.sender].owner] += charge; } function executeCallWithGas(uint allowed_gas, address to, uint256 value, bytes memory data) internal returns (bool success) { assembly { success := call(allowed_gas, to, value, add(data, 0x20), mload(data), 0, 0) } } struct Transaction { uint nonce; uint gas_price; uint gas_limit; address to; uint value; bytes data; } function decode_transaction (bytes memory raw_transaction) private pure returns ( Transaction memory transaction) { (transaction.nonce,transaction.gas_price,transaction.gas_limit,transaction.to, transaction.value, transaction.data) = RLPReader.decode_transaction(raw_transaction); return transaction; } function penalize_repeated_nonce(bytes memory unsigned_tx1, bytes memory sig1 ,bytes memory unsigned_tx2, bytes memory sig2) public { // Can be called by anyone. // If a relay attacked the system by signing multiple transactions with the same nonce (so only one is accepted), anyone can grab both transactions from the blockchain and submit them here. // Check whether unsigned_tx1 != unsigned_tx2, that both are signed by the same address, and that unsigned_tx1.nonce == unsigned_tx2.nonce. If all conditions are met, relay is considered an "offending relay". // The offending relay will be unregistered immediately, its stake will be forfeited and given to the address who reported it (msg.sender), thus incentivizing anyone to report offending relays. // If reported via a relay, the forfeited stake is split between msg.sender (the relay used for reporting) and the address that reported it. Transaction memory decoded_tx1 = decode_transaction(unsigned_tx1); Transaction memory decoded_tx2 = decode_transaction(unsigned_tx2); bytes32 hash1 = keccak256(abi.encodePacked(unsigned_tx1)); address addr1 = ecrecover(hash1, uint8(sig1[0]), bytesToBytes32(sig1,1), bytesToBytes32(sig1,33)); bytes32 hash2 = keccak256(abi.encodePacked(unsigned_tx2)); address addr2 = ecrecover(hash2, uint8(sig2[0]), bytesToBytes32(sig2,1), bytesToBytes32(sig2,33)); //checking that the same nonce is used in both transaction, with both signed by the same address and the actual data is different // note: we compare the hash of the data to save gas over iterating both byte arrays require( decoded_tx1.nonce == decoded_tx2.nonce, "Different nonce"); require(addr1 == addr2, "Different signer"); require(keccak256(abi.encodePacked(decoded_tx1.data)) != keccak256(abi.encodePacked(decoded_tx2.data)), "tx.data is equal" ) ; // Checking that we do have addr1 as a staked relay require( stakes[addr1].stake > 0, "Unstaked relay" ); // Checking that the relay wasn't penalized yet require(!stakes[addr1].removed, "Relay already penalized"); // compensating the sender with the stake of the relay uint amount = stakes[addr1].stake; // move ownership of relay stakes[addr1].owner = msg.sender; emit Penalized(addr1, msg.sender, amount); remove_relay_by_owner(addr1); } function bytesToBytes32(bytes memory b, uint offset) private pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } }
Create or increase the stake and unstake_delay Make sure that the relay doesn't decrease his delay if already registered
function stake(address relay, uint unstake_delay) external payable { require(stakes[relay].owner == address(0) || stakes[relay].owner == msg.sender, "not owner"); stakes[relay].owner = msg.sender; stakes[relay].stake += msg.value; require(unstake_delay >= stakes[relay].unstake_delay, "unstake_delay cannot be decreased"); stakes[relay].unstake_delay = unstake_delay; validate_stake(relay); emit Staked(relay, msg.value); }
5,540,049
[ 1, 1684, 578, 10929, 326, 384, 911, 471, 640, 334, 911, 67, 10790, 4344, 3071, 716, 326, 18874, 3302, 1404, 20467, 18423, 4624, 309, 1818, 4104, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 384, 911, 12, 2867, 18874, 16, 2254, 640, 334, 911, 67, 10790, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 334, 3223, 63, 2878, 528, 8009, 8443, 422, 1758, 12, 20, 13, 747, 384, 3223, 63, 2878, 528, 8009, 8443, 422, 1234, 18, 15330, 16, 315, 902, 3410, 8863, 203, 3639, 384, 3223, 63, 2878, 528, 8009, 8443, 273, 1234, 18, 15330, 31, 203, 3639, 384, 3223, 63, 2878, 528, 8009, 334, 911, 1011, 1234, 18, 1132, 31, 203, 3639, 2583, 12, 23412, 911, 67, 10790, 1545, 384, 3223, 63, 2878, 528, 8009, 23412, 911, 67, 10790, 16, 315, 23412, 911, 67, 10790, 2780, 506, 23850, 8905, 8863, 203, 3639, 384, 3223, 63, 2878, 528, 8009, 23412, 911, 67, 10790, 273, 640, 334, 911, 67, 10790, 31, 203, 3639, 1954, 67, 334, 911, 12, 2878, 528, 1769, 203, 3639, 3626, 934, 9477, 12, 2878, 528, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; interface IUniswapV2Router02 { function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function WETH() external pure returns (address); } contract JPEGvaultDAOTokenV2 is ERC20SnapshotUpgradeable, OwnableUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; EnumerableSetUpgradeable.AddressSet private excludedRedistribution; // exclure de la redistribution mapping(address => bool) private excludedTax; IUniswapV2Router02 private m_UniswapV2Router; address private uniswapV2Pair; address private WETHAddr; address private growthAddress; address private vaultAddress; address private liquidityAddress; address private redistributionContract; uint8 private growthFees; uint8 private vaultFees; uint8 private liquidityFees; uint8 private autoLiquidityFees; // Autoselling ratio between 0 and 100 uint8 private autoSellingRatio; uint216 private minAmountForSwap; // Stores tokens waiting for the next swap uint private autoSellGrowthStack; uint private autoSellVaultStack; uint private autoSellLiquidityStack; function initialize(address _growthAddress, address _vaultAddress, address _liquidityAddress, address _router) external initializer { __Ownable_init(); __ERC20_init("JPEG", "JPEG"); __ERC20Snapshot_init(); m_UniswapV2Router = IUniswapV2Router02(_router); WETHAddr = m_UniswapV2Router.WETH(); growthAddress = _growthAddress; _transferOwnership(growthAddress); vaultAddress = _vaultAddress; liquidityAddress = _liquidityAddress; excludedRedistribution.add(address(this)); excludedRedistribution.add(growthAddress); excludedRedistribution.add(vaultAddress); excludedRedistribution.add(liquidityAddress); excludedTax[address(this)] = true; excludedTax[growthAddress] = true; excludedTax[vaultAddress] = true; excludedTax[liquidityAddress] = true; growthFees = 2; vaultFees = 6; liquidityFees = 1; autoLiquidityFees = 1; minAmountForSwap = 1000; autoSellingRatio = 70; _mint(growthAddress, 1000000000 * 10 ** 18); } receive() external payable {} function _transfer( address sender, address recipient, uint256 amount ) internal override { if (!excludedTax[sender] && !excludedTax[recipient]) { amount = applyTaxes(sender, amount); } super._transfer(sender, recipient, amount); } function applyTaxes(address sender, uint amount) internal returns (uint newAmountTransfer) { uint amountGrowth = amount * growthFees; uint amountVault = amount * vaultFees; uint amountLiquidity = amount * liquidityFees; uint amountAutoLiquidity = amount * autoLiquidityFees; // Cheaper without "no division by 0" check unchecked { amountGrowth /= 100; amountVault /= 100; amountLiquidity /= 100; amountAutoLiquidity /= 100; } newAmountTransfer = amount - amountGrowth - amountVault - amountLiquidity - amountAutoLiquidity; // Apply autoselling ratio uint autoSellGrowth = amountGrowth * autoSellingRatio; uint autoSellVault = amountVault * autoSellingRatio; uint autoSellLiquidity = amountLiquidity * autoSellingRatio; // Cheaper without "no division by 0" check unchecked { autoSellGrowth /= 100; autoSellVault /= 100; autoSellLiquidity /= 100; } // Transfer the remaining tokens to wallets super._transfer(sender, growthAddress, amountGrowth - autoSellGrowth); super._transfer(sender, vaultAddress, amountVault - autoSellVault); super._transfer(sender, liquidityAddress, amountLiquidity - autoSellLiquidity); // Transfer all autoselling + autoLP to the contract super._transfer(sender, address(this), autoSellGrowth + autoSellVault + autoSellLiquidity + amountAutoLiquidity); uint tokenBalance = balanceOf(address(this)); // Only swap if it's worth it if (tokenBalance >= (minAmountForSwap * 1 ether) && uniswapV2Pair != address(0) && uniswapV2Pair != msg.sender) { swapAndLiquify(tokenBalance, autoSellGrowth, autoSellVault, autoSellLiquidity); } else { // Stack tokens to be swapped for autoselling autoSellGrowthStack = autoSellGrowthStack + autoSellGrowth; autoSellVaultStack = autoSellVaultStack + autoSellVault; autoSellLiquidityStack = autoSellLiquidityStack + autoSellLiquidity; } } function swapAndLiquify(uint tokenBalance, uint autoSellGrowth, uint autoSellVault, uint autoSellLiquidity) internal { uint finalAutoSellGrowth = autoSellGrowthStack + autoSellGrowth; uint finalAutoSellVault = autoSellVaultStack + autoSellVault; uint finalAutoSellLiquidity = autoSellLiquidityStack + autoSellLiquidity; uint totalStacked = finalAutoSellGrowth + finalAutoSellVault + finalAutoSellLiquidity; uint amountToLiquifiy = tokenBalance - totalStacked; // Stack tokens for autoliquidity pool uint tokensToBeSwappedForLP; unchecked { tokensToBeSwappedForLP = amountToLiquifiy / 2; } uint tokensForLP = amountToLiquifiy - tokensToBeSwappedForLP; uint totalToSwap = totalStacked + tokensToBeSwappedForLP; // Swap all in one call uint balanceInEth = address(this).balance; swapTokensForEth(totalToSwap); uint totalETHswaped = address(this).balance - balanceInEth; // Redistribute according to weigth uint growthETH = totalETHswaped * finalAutoSellGrowth / totalToSwap; uint vaultETH = totalETHswaped * finalAutoSellVault / totalToSwap; uint liquidityETH = totalETHswaped * finalAutoSellLiquidity / totalToSwap; AddressUpgradeable.sendValue(payable(growthAddress), growthETH); AddressUpgradeable.sendValue(payable(vaultAddress), vaultETH); AddressUpgradeable.sendValue(payable(liquidityAddress), liquidityETH); uint availableETHForLP = totalETHswaped - growthETH - vaultETH - liquidityETH; addLiquidity(tokensForLP, availableETHForLP); autoSellGrowthStack = 0; autoSellVaultStack = 0; autoSellLiquidityStack = 0; } function addLiquidity(uint tokenAmount, uint ethAmount) internal { // add liquidity with token and ETH _approve(address(this), address(m_UniswapV2Router), tokenAmount); m_UniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, owner(), block.timestamp ); } function swapTokensForEth(uint256 amount) private { address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = address(WETHAddr); _approve(address(this), address(m_UniswapV2Router), amount); m_UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, _path, address(this), block.timestamp ); } function createRedistribution() public returns (uint, uint) { require(msg.sender == redistributionContract, "Bad caller"); uint newSnapshotId = _snapshot(); return (newSnapshotId, calcSupplyHolders()); } function calcSupplyHolders() internal view returns (uint) { uint balanceExcluded = 0; for (uint i = 0; i < excludedRedistribution.length(); i++) balanceExcluded += balanceOf(excludedRedistribution.at(i)); return totalSupply() - balanceExcluded; } // Tax management function setGrowthFees(uint8 _fees) external onlyOwner { growthFees = _fees; } function setVaultFees(uint8 _fees) external onlyOwner { vaultFees = _fees; } function setLiquidityFees(uint8 _fees) external onlyOwner { liquidityFees = _fees; } function setGrowthAddress(address _address) external onlyOwner { growthAddress = _address; excludedRedistribution.add(_address); excludedTax[_address] = true; } function setVaultAddress(address _address) external onlyOwner { vaultAddress = _address; excludedRedistribution.add(_address); excludedTax[_address] = true; } function setLiquidityAddress(address _address) external onlyOwner { liquidityAddress = _address; excludedRedistribution.add(_address); excludedTax[_address] = true; } function excludeTaxAddress(address _address) external onlyOwner { excludedTax[_address] = true; } function removeTaxAddress(address _address) external onlyOwner { require(_address != address(this), "Not authorized to remove the contract from tax"); excludedTax[_address] = false; } // Liquidity settings function setAutoLiquidityFees(uint8 _fees) external onlyOwner { autoLiquidityFees = _fees; } function setMinAmountForSwap(uint216 _amount) external onlyOwner { minAmountForSwap = _amount; } function setUniswapV2Pair(address _pair) external onlyOwner { uniswapV2Pair = _pair; excludedRedistribution.add(_pair); } function setAutoSellingRatio(uint8 ratio) external onlyOwner{ require(autoSellingRatio <= 100, "autoSellingRatio should be lower than 100"); autoSellingRatio = ratio; } // Redistribution management function setRedistributionContract(address _address) external onlyOwner { redistributionContract = _address; excludedRedistribution.add(_address); excludedTax[_address] =true; } function removeRedistributionAddress(address _address) external onlyOwner { excludedRedistribution.remove(_address); } function excludedRedistributionAddress(address _address) external onlyOwner { excludedRedistribution.add(_address); } }
Transfer the remaining tokens to wallets
super._transfer(sender, growthAddress, amountGrowth - autoSellGrowth);
2,529,762
[ 1, 5912, 326, 4463, 2430, 358, 17662, 2413, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2240, 6315, 13866, 12, 15330, 16, 13334, 451, 1887, 16, 3844, 30948, 451, 300, 3656, 55, 1165, 30948, 451, 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 ]
./full_match/42220/0xc6BBA245CbB235Af7B869eEf08ABA1f5A2c5C493/sources/Haiex.sol
Initialize ERC20 tokenGet stable informationGet sender balanceCheck amount, Balance, allowance, token price, existenceFist step convert Stable1 to USDSmart contract Burn those tokensDecrease usd reserve allocate to Stable1Calculate TaxesGet TaxTransfer taxSecond step convert USD to Stable2Smart contract Mint the Stable2Update reserve allocate to Stable2Operation successful
function stableTrade(address _stable1, address _stable2, uint256 amount) public whenNotPaused returns (bool) { Model stableCoin1 = Model(_stable1); Model stableCoin2 = Model(_stable2); Stable memory stable1 = getStableByAddress(stableCoin1); Stable memory stable2 = getStableByAddress(stableCoin2); uint senderBalance = stableCoin1.balanceOf(msg.sender); require(_stable1 != address(0), "Stable1 doest not exist"); require(_stable2 != address(0), "Stable2 doest not exist"); require(amount > 0, "Amount can't be zero"); require(senderBalance >= amount, "Token not enough"); require(stableCoin1.allowance(msg.sender, address(this)) >= amount, "Allowance not enough"); require(stable1.price > 0, "Stable1 Price has not been define"); require(stable2.price > 0, "Stable2 Price has not been define"); uint256 usd = mul(div(amount, stable1.price), priceFloatDigit); stableCoin1.burnFrom(msg.sender, amount); updateStableReserve(stable1.tokenAddress, usd, Operation.SUB); uint taxes = div(mul(usd, tradeFees), 10**4); uint usdr = usd - taxes; USDToken.transfer(address(manager), div(taxes, 2)); uint256 tokens = div(mul(usdr, stable2.price), priceFloatDigit); stableCoin2.mint(msg.sender, tokens); updateStableReserve(stable2.tokenAddress, usdr, Operation.ADD); return true; }
16,332,225
[ 1, 7520, 4232, 39, 3462, 1147, 967, 14114, 1779, 967, 5793, 11013, 1564, 3844, 16, 30918, 16, 1699, 1359, 16, 1147, 6205, 16, 15782, 42, 376, 2235, 1765, 934, 429, 21, 358, 11836, 3948, 81, 485, 6835, 605, 321, 5348, 2430, 23326, 448, 584, 72, 20501, 10101, 358, 225, 934, 429, 21, 8695, 399, 10855, 967, 18240, 5912, 5320, 8211, 2235, 1765, 587, 9903, 358, 934, 429, 22, 23824, 6835, 490, 474, 326, 934, 429, 22, 1891, 20501, 10101, 358, 225, 934, 429, 22, 2988, 6873, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14114, 22583, 12, 2867, 389, 15021, 21, 16, 1758, 389, 15021, 22, 16, 2254, 5034, 3844, 13, 1071, 225, 1347, 1248, 28590, 1135, 261, 6430, 13, 288, 203, 203, 377, 203, 1377, 203, 3639, 3164, 14114, 27055, 21, 273, 3164, 24899, 15021, 21, 1769, 203, 3639, 3164, 14114, 27055, 22, 273, 3164, 24899, 15021, 22, 1769, 203, 203, 3639, 934, 429, 3778, 14114, 21, 273, 21491, 429, 858, 1887, 12, 15021, 27055, 21, 1769, 203, 3639, 934, 429, 3778, 14114, 22, 273, 21491, 429, 858, 1887, 12, 15021, 27055, 22, 1769, 203, 203, 203, 203, 3639, 2254, 5793, 13937, 273, 14114, 27055, 21, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 540, 203, 203, 3639, 2583, 24899, 15021, 21, 480, 1758, 12, 20, 3631, 315, 30915, 21, 741, 395, 486, 1005, 8863, 203, 3639, 2583, 24899, 15021, 22, 480, 1758, 12, 20, 3631, 315, 30915, 22, 741, 395, 486, 1005, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 6275, 848, 1404, 506, 3634, 8863, 203, 3639, 2583, 12, 15330, 13937, 1545, 3844, 16, 315, 1345, 486, 7304, 8863, 203, 3639, 2583, 12, 15021, 27055, 21, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 3844, 16, 315, 7009, 1359, 486, 7304, 8863, 203, 3639, 2583, 12, 15021, 21, 18, 8694, 405, 374, 16, 315, 30915, 21, 20137, 711, 486, 2118, 4426, 8863, 203, 3639, 2583, 12, 15021, 22, 18, 8694, 405, 374, 16, 315, 30915, 22, 20137, 711, 486, 2118, 4426, 8863, 203, 203, 203, 2 ]
pragma solidity ^0.5.11; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } /// @title Kyber Network interface interface KyberNetworkProxyInterface { function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); } /// @title Compound Finance interface interface CERC20 { function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); function underlying() external view returns (address); } /// @title Ownable Contract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "caller must be the Contract Owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "New Owner must not be empty."); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /// @title Memento Fund Contract contract Mementofund is Ownable { using SafeMath for uint256; //variables uint minRate; // uint256 public totalFundsInDAI; uint256 public developerFeeRate; uint public managerTransactionFee; uint public managerFundFee; uint accountIndexMax; uint userTokenCount; //Events event managerAddressUpdated(address newaddress); event kybertrade(address _src, uint256 _amount, address _dest, uint256 _destqty); event deposit(ERC20 _src, uint256 _amount); // addresses address public DAI_ADDR; address payable public CDAI_ADDR; address payable public KYBER_ADDR; address payable public ADMIN_ADDR; address payable public COMPOUND_ADDR; // Interfaces ERC20 internal dai; KyberNetworkProxyInterface internal kyber; CERC20 internal CDai; bytes public constant PERM_HINT = "PERM"; // Constants ERC20 internal constant ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal ETH_DECIMALS = 18; uint constant internal MAX_DECIMALS = 18; //Structs struct Account{ address payable benefactorAddress; string benefactorName; address payable managerAddress; address[] signatories; uint creationDate; uint unlockDate; uint preUnlockMonthlyquota; } struct Investment{ uint256 timestamp; address depositedBy; address srcTokenAddress; uint256 srcAmount; address destTokenAddress; uint256 destAmount; } struct Memory{ uint256 timestamp; address depositedBy; bytes ipfshash; string memoryText; string filetype; } //Mappings //Account Tracking mapping(address => mapping(uint => address)) public usertokenMapping; mapping(address => uint) public userTokens; mapping(address => mapping(address => uint256)) public userBalance; mapping(address => Account) public accounts; mapping(address => Investment[]) public userInvestments; // mapping(address => address) uniswapExchange; constructor( address payable _adminAddr, address _daiAddr, address payable _kyberAddr, address payable _cdaiAddr ) public { KYBER_ADDR = _kyberAddr; ADMIN_ADDR = _adminAddr; CDAI_ADDR = _cdaiAddr; DAI_ADDR = _daiAddr; dai = ERC20(DAI_ADDR); CDai = CERC20(CDAI_ADDR); kyber = KyberNetworkProxyInterface(_kyberAddr); // compound = Compound(_compoundAddr); bool daiApprovalResult = dai.approve(DAI_ADDR, 2**256-1); require(daiApprovalResult, "Failed to approve cDAI contract to spend DAI"); } // Internal Utilities modifier onlyFundAdmin() { require(isFundAdmin(), "Only Fund Manger is Authorised to execute that function."); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isFundAdmin() public view returns (bool) { return msg.sender == ADMIN_ADDR; } function isRegisteredBenefactor(address _account) public view returns (bool) { if (accounts[_account].benefactorAddress != address(0x00)){ return true; } } function isAccountManager(address _account) public view returns (bool) { if (accounts[_account].managerAddress == msg.sender){ return true; } } function handleIndexes(address _account, address _token) internal { if (userBalance[_account][_token] == 0x00) { usertokenMapping[_account][userTokens[_account]] = _token; userTokens[_account] += 1; } } //Account Management Functions function registerAccount(address payable _benefactorAddress, string memory _benefactorName, address payable _managerAddress, address[] memory _signatories, uint _unlockDate, uint _preUnlockMonthlyquota) public returns(bool) { if (accounts[_benefactorAddress].benefactorAddress == address(0x00)){ Account storage account = accounts[_benefactorAddress]; account.benefactorAddress = _benefactorAddress; account.benefactorName = _benefactorName; account.managerAddress = _managerAddress; account.signatories = _signatories; account.creationDate = now; account.unlockDate = _unlockDate; account.preUnlockMonthlyquota = _preUnlockMonthlyquota; } } // Kyber Trading Function function _kybertrade(ERC20 _srcToken, uint256 _srcAmount, ERC20 _destToken) internal returns( uint256 _actualDestAmount ) { require(_srcToken != _destToken, "Source matches Destination."); uint256 msgValue; uint256 rate; if (_srcToken != ETH_TOKEN_ADDRESS) { msgValue = 0; _srcToken.approve(KYBER_ADDR, 0); _srcToken.approve(KYBER_ADDR, _srcAmount); } else { msgValue = _srcAmount; } (,rate) = kyber.getExpectedRate(_srcToken, _destToken, _srcAmount); _actualDestAmount = kyber.tradeWithHint.value(msgValue)( _srcToken, _srcAmount, _destToken, address(uint160(address(this))), MAX_QTY, rate, address(0), PERM_HINT ); require(_actualDestAmount > 0, "Destination value must be greater than 0"); if (_srcToken != ETH_TOKEN_ADDRESS) { _srcToken.approve(KYBER_ADDR, 0); } } function investEthToDai(address _account) public payable returns (bool) { require(isRegisteredBenefactor(_account),"Specified account must be registered."); handleIndexes(_account, address(DAI_ADDR)); uint256 destqty = _kybertrade(ETH_TOKEN_ADDRESS, msg.value, dai); userBalance[_account][address(DAI_ADDR)] = userBalance[_account][address(DAI_ADDR)].add(destqty); userInvestments[_account].push(Investment({ timestamp: now, depositedBy: msg.sender, srcTokenAddress: address(ETH_TOKEN_ADDRESS), srcAmount: msg.value, destTokenAddress: address(DAI_ADDR), destAmount: destqty })); emit kybertrade(address(ETH_TOKEN_ADDRESS), msg.value, DAI_ADDR, destqty); return true; } function investEthToToken(address _account, ERC20 _token) external payable returns (bool) { require(isRegisteredBenefactor(_account),"Sepcified account must be registered"); handleIndexes(_account, address(_token)); uint256 destqty = _kybertrade(ETH_TOKEN_ADDRESS, msg.value, _token); userBalance[_account][address(_token)] = userBalance[_account][address(_token)].add(destqty); userInvestments[_account].push(Investment({ timestamp: now, depositedBy: msg.sender, srcTokenAddress: address(ETH_TOKEN_ADDRESS), srcAmount: msg.value, destTokenAddress: address(_token), destAmount: destqty })); emit kybertrade(address(ETH_TOKEN_ADDRESS), msg.value, address(_token), destqty); return true; } function investToken(address _account, ERC20 _token, uint256 _amount) external returns (bool) { require(isRegisteredBenefactor(_account),"Specified account must be registered"); require(_token.balanceOf(msg.sender) >= _amount, "Sender balance Too Low."); require(_token.approve(address(this), _amount), "Fund not approved to transfer senders Token Balance"); require(_token.transfer(address(this), _amount), "Sender hasn'tr transferred tokens."); handleIndexes(_account, address(_token)); userBalance[_account][address(_token)] = userBalance[_account][address(_token)].add(_amount); userInvestments[_account].push(Investment({ timestamp: now, depositedBy: msg.sender, srcTokenAddress: address(_token), srcAmount: _amount, destTokenAddress: address(_token), destAmount: _amount })); return true; } function investTokenToToken(address _account, ERC20 _token, uint256 _amount, ERC20 _dest) external returns (bool) { require(isRegisteredBenefactor(_account), "Specified account must be registered"); require(_token.balanceOf(msg.sender) >= _amount, "Account token balance must be greater that spscified amount"); require(_token.approve(address(this), _amount), "Contract must be approved to transfer Specified token"); require(_token.transfer(address(this), _amount), "Specified Token must be tranferred from caller to contract"); handleIndexes(_account, address(_token)); uint destqty = _kybertrade(_token, _amount, _dest); userBalance[_account][address(_token)] = userBalance[_account][address(_token)].add(destqty); userInvestments[_account].push(Investment({ timestamp: now, depositedBy: msg.sender, srcTokenAddress: address(_token), srcAmount: _amount, destTokenAddress: address(_dest), destAmount: destqty })); emit deposit(_dest, destqty); return true; } function splitInvestEthToToken(address _account, address[] memory _tokens, uint[] memory _ratios) public payable { require(isRegisteredBenefactor(_account),"Specified account must be registered"); require(msg.value > 0, "Transaction must have ether value"); require(_tokens.length == _ratios.length, "unmatched array lengths"); handleIndexes(_account, address(ETH_TOKEN_ADDRESS)); uint256 msgValue = msg.value; require(_tokens.length > 0, "Array must be greater than 0."); uint quotaTotal; for (uint i = 0;i < _tokens.length; i++) { quotaTotal = quotaTotal.add(quotaTotal); } require(quotaTotal < 100, "Split Total Greater than 100."); for (uint i = 0; i < _tokens.length; i++) { handleIndexes(_account, address(_tokens[i])); uint256 quota = (msg.value * _ratios[i]) / 100; require(quota < msg.value, "Quota Split greater than Message Value"); uint destqty = _kybertrade(ETH_TOKEN_ADDRESS, quota, ERC20(_tokens[i])); userBalance[_account][address(_tokens[i])] = userBalance[_account][address(_tokens[i])].add(destqty); userInvestments[_account].push(Investment({ timestamp: now, depositedBy: msg.sender, srcTokenAddress: address(ETH_TOKEN_ADDRESS), srcAmount: quota, destTokenAddress: address(_tokens[i]), destAmount: destqty })); msgValue = msgValue.sub(quota); emit kybertrade(address(ETH_TOKEN_ADDRESS),quota, address(_tokens[i]), destqty); } userBalance[_account][address(ETH_TOKEN_ADDRESS)] = userBalance[_account][address(ETH_TOKEN_ADDRESS)].add(msgValue); userInvestments[_account].push(Investment({ timestamp: now, depositedBy: msg.sender, srcTokenAddress: address(ETH_TOKEN_ADDRESS), srcAmount: msgValue, destTokenAddress: address(ETH_TOKEN_ADDRESS), destAmount: msgValue })); } function swapTokenToEther (address _account, ERC20 _src, uint _amount) public { require(isAccountManager(_account),"Caller must be registered as an Account Manager"); uint destqty = _kybertrade(_src, _amount, ETH_TOKEN_ADDRESS); userBalance[_account][address(_src)] = userBalance[_account][address(_src)].sub(_amount); userBalance[_account][address(ETH_TOKEN_ADDRESS)] = userBalance[_account][address(ETH_TOKEN_ADDRESS)].add(destqty); emit kybertrade(address(_src), _amount, address(ETH_TOKEN_ADDRESS), destqty); } function swapEtherToToken (address _account, ERC20 _dest, uint _amount) public { require(isAccountManager(_account),"Caller must be registered as an Account Manager"); uint destqty = _kybertrade(ETH_TOKEN_ADDRESS, _amount, _dest); userBalance[_account][address(_dest)] = userBalance[_account][address(_dest)].add(destqty); userBalance[_account][address(ETH_TOKEN_ADDRESS)] = userBalance[_account][address(ETH_TOKEN_ADDRESS)].sub(_amount); emit kybertrade(address(ETH_TOKEN_ADDRESS), _amount, address(_dest), destqty); } function swapTokenToToken(address _account, ERC20 _src, uint256 _amount, ERC20 _dest) public { require(isAccountManager(_account),"Caller must be registered as an Account Manager"); uint destqty = _kybertrade(_src, _amount, _dest); userBalance[_account][address(_src)] = userBalance[_account][address(_src)].sub(_amount); userBalance[_account][address(_dest)] = userBalance[_account][address(_dest)].add(destqty); emit kybertrade(address(_src), _amount, address(_dest), destqty); } //Fund Admin Functions function updateAdminAddress(address payable _newaddress) external onlyFundAdmin returns (bool) { require(_newaddress != address(0),"New admin address must not be blank"); require(_newaddress != ADMIN_ADDR, "New admin addres must not be current admin address"); ADMIN_ADDR = _newaddress; emit managerAddressUpdated(_newaddress); } function updateDaiAddress(address payable _newaddress) external onlyFundAdmin returns (bool) { require(_newaddress != address(0),"New admin address must not be blank"); require(_newaddress != DAI_ADDR, "New DAI Contract adress must not be current DAI Contract Address"); DAI_ADDR = _newaddress; } function updateKyberAddress(address payable _newaddress) external onlyFundAdmin returns (bool) { require(_newaddress != address(0),"New admin address must not be blank"); require(_newaddress != KYBER_ADDR, "New KYBER Contract address must be different from old Contract Address"); KYBER_ADDR = _newaddress; } // function lend(address _account, ) function getBalance(address _account, ERC20 _token) public view returns(uint256) { return userBalance[_account][address(_token)]; } function withdraw(address payable _account, ERC20 _token, uint256 _amount) public { require(isRegisteredBenefactor(address(_account))); require(now > accounts[_account].unlockDate); require(userBalance[msg.sender][address(_token)] >= _amount); if (_token == ETH_TOKEN_ADDRESS) { userBalance[msg.sender][address(_token)] = userBalance[msg.sender][address(_token)].sub(_amount); msg.sender.transfer(_amount); } else { userBalance[msg.sender][address(_token)] = userBalance[msg.sender][address(_token)].sub(_amount); _token.transfer(msg.sender, _amount); } } function closeaccount(address payable _account) public { require(isRegisteredBenefactor(_account)); require(block.timestamp > accounts[_account].unlockDate); require(userTokens[_account] > 0, "User Tokens must be greater than 0"); for (uint i = 0; i < userTokens[msg.sender]; i++) { address token = usertokenMapping[msg.sender][i]; uint256 balance = userBalance[msg.sender][token]; withdraw(_account, ERC20(token), balance); } } //Management functions //fallback - send eth to manager so he can refund sender function () external payable { userBalance[ADMIN_ADDR][address(ETH_TOKEN_ADDRESS)] = userBalance[ADMIN_ADDR][address(ETH_TOKEN_ADDRESS)].add(msg.value); } }
@title Kyber Network interface
interface KyberNetworkProxyInterface { function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); }
12,949,646
[ 1, 47, 93, 744, 5128, 1560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 1475, 93, 744, 3906, 3886, 1358, 288, 203, 565, 445, 336, 6861, 4727, 12, 654, 39, 3462, 1705, 16, 4232, 39, 3462, 1570, 16, 2254, 1705, 53, 4098, 13, 3903, 1476, 1135, 261, 11890, 2665, 4727, 16, 2254, 272, 3169, 2433, 4727, 1769, 203, 565, 445, 18542, 1190, 7002, 12, 654, 39, 3462, 1705, 16, 2254, 1705, 6275, 16, 4232, 39, 3462, 1570, 16, 1758, 1570, 1887, 16, 203, 5411, 2254, 943, 9378, 6275, 16, 2254, 1131, 6814, 4727, 16, 1758, 9230, 548, 16, 1731, 745, 892, 7380, 13, 3903, 8843, 429, 1135, 12, 11890, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xf123EF547D8478265e56a10917CCAd6Ab67817b7/sources/contracts/FVCKCRYSTAL.sol
* @dev Withdraw funds/
function withdraw(address payable recipient, uint256 amount) external adminRequired { recipient.transfer(amount); }
7,041,887
[ 1, 1190, 9446, 284, 19156, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 3903, 3981, 3705, 288, 203, 3639, 8027, 18, 13866, 12, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.1; import "./ICampaignFactory.sol"; import "./AggregatorV3Interface.sol"; import "./Ownable.sol"; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./IERC20.sol"; import "./Pausable.sol"; contract Campaign is Ownable, ReentrancyGuard, Pausable { using SafeMath for uint256; // Token being sold IERC20 public token; // Address of factory contract address public factory; // Address where funds are collected address public fundingWallet; // Timestamp when token started to sell uint256 public openTime = block.timestamp; // Timestamp when token stopped to sell uint256 public closeTime; // Timestamp when token release is enabled uint256 public releaseTime; // Amount of wei raised uint256 public weiRaised = 0; // Amount of tokens sold uint256 public tokenSold = 0; // Amount of tokens claimed uint256 public tokenClaimed = 0; // Name of IDO Campaign string public name; // Ether to token conversion rate uint256 private etherConversionRate; // Ether to token conversion rate decimals uint256 private etherConversionRateDecimals = 0; // Chainlink Price Feed AggregatorV3Interface internal EthPriceFeed; // Token to token conversion rate mapping(IERC20 => uint256) private erc20TokenConversionRate; // Token sold mapping to delivery mapping(address => uint256) private tokenSoldMapping; modifier tokenRateSet(IERC20 _token) { require( erc20TokenConversionRate[_token] != 0, "ICO_CAMPAIGN::TOKEN_NOT_ALLOWED" ); _; } // ----------------------------------------- // Lemonade's events // ----------------------------------------- event CampaignCreated( string name, address token, uint256 openTime, uint256 closeTime, uint256 releaseTime, uint256 ethRate, uint256 ethRateDecimals, address wallet, address owner ); event AllowTokenToTradeWithRate(address token, uint256 rate); event TokenPurchaseByEther( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event TokenPurchaseByToken( address indexed purchaser, address indexed beneficiary, address token, uint256 value, uint256 amount ); event RefundedTokenForIcoWhenEndIco(address wallet, uint256 amount); event TokenClaimed(address wallet, uint256 amount); event CampaignStatsChanged(); // ----------------------------------------- // Constructor // ----------------------------------------- constructor() { factory = msg.sender; // Kovan Chainlink Address: // Main net: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 EthPriceFeed = AggregatorV3Interface( 0x9326BFA02ADD2366b30bacB125260Af641031331 ); } // ----------------------------------------- // Lemonade external interface // ----------------------------------------- /** * @dev fallback function */ fallback() external { revert(); } /** * @dev fallback function */ receive() external payable { buyTokenByEther(msg.sender); } /** * @param _name Name of ICO Campaign * @param _token Address of the token being sold * @param _duration Duration of ICO Campaign * @param _openTime When ICO Started * @param _ethRate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to */ function initialize( string calldata _name, IERC20 _token, uint256 _duration, uint256 _openTime, uint256 _releaseTime, uint256 _ethRate, uint256 _ethRateDecimals, address _wallet ) external { require(msg.sender == factory, "ICO_CAMPAIGN::UNAUTHORIZED"); name = _name; token = _token; openTime = _openTime; closeTime = _openTime.add(_duration); releaseTime = _releaseTime; etherConversionRate = _ethRate; etherConversionRateDecimals = _ethRateDecimals; fundingWallet = _wallet; owner = tx.origin; paused = false; emit CampaignCreated( name, address(token), openTime, closeTime, releaseTime, etherConversionRate, etherConversionRateDecimals, fundingWallet, owner ); } /** * @notice Returns the conversion rate when user buy by eth * @return Returns only a fixed number of rate. */ function getEtherConversionRate() public view returns (uint256) { return etherConversionRate; } /** * @notice Returns the conversion rate decimals when user buy by eth * @return Returns only a fixed number of decimals. */ function getEtherConversionRateDecimals() public view returns (uint256) { return etherConversionRateDecimals; } /** * @notice Returns the conversion rate when user buy by eth * @return Returns only a fixed number of token rate. * @param _token address of token to query token exchange rate */ function getErc20TokenConversionRate(IERC20 _token) public view returns (uint256) { return erc20TokenConversionRate[_token]; } /** * @notice Returns the Buyable tokens of an address * @return Returns amount of tokens the user can buy * @param _address Address to find the amount of tokens */ function getBuyableTokens(address _address) public view returns (uint256) { return etherConversionRate .mul(1 ether) .mul(100000000000) .div(getLatestEthPrice()) .div(10**etherConversionRateDecimals) .sub(tokenSoldMapping[_address]); } /** * @notice Returns the available tokens of Campaign * @return Returns amount of tokens available to buy in the Campaign */ function getAvailableTokens() public view returns (uint256) { return token.balanceOf(address(this)).add(tokenClaimed).sub(tokenSold); } /** * @notice Returns the total tokens of Campaign * @return Returns amount of tokens need to sold out the Campaign */ function totalRaisedTokens() public view returns (uint256) { return token.balanceOf(address(this)).add(tokenClaimed); } /** * @notice Returns the Claimable tokens of an address * @return Returns amount of tokens the user can calain * @param _address Address to find the amount of tokens */ function getClaimableTokens(address _address) public view returns (uint256) { return tokenSoldMapping[_address]; } /** * @notice Allows the contract to get the latest value of the ETH/USD price feed * @return Returns the latest ETH/USD price */ function getLatestEthPrice() public view returns (uint256) { (, int256 price, , , ) = EthPriceFeed.latestRoundData(); return uint256(price); } /** * @notice Owner can set the eth conversion rate. Receiver tokens = wei * etherConversionRate / 10 ** etherConversionRateDecimals * @param _rate Fixed number of ether rate */ function setEtherConversionRate(uint256 _rate) external onlyOwner { require(etherConversionRate != _rate, "ICO_CAMPAIGN::RATE_INVALID"); etherConversionRate = _rate; emit CampaignStatsChanged(); } /** * @notice Owner can set the eth conversion rate with decimals * @param _rate Fixed number of ether rate * @param _rateDecimals Fixed number of ether rate decimals */ function setEtherConversionRateAndDecimals(uint256 _rate, uint256 _rateDecimals) external onlyOwner { etherConversionRate = _rate; etherConversionRateDecimals = _rateDecimals; emit CampaignStatsChanged(); } /** * @notice Owner can set the eth conversion rate decimals. Receiver tokens = wei * etherConversionRate / 10 ** etherConversionRateDecimals * @param _rateDecimals Fixed number of ether rate decimals */ function setEtherConversionRateDecimals(uint256 _rateDecimals) external onlyOwner { etherConversionRateDecimals = _rateDecimals; emit CampaignStatsChanged(); } /** * @notice Owner can set the new Chainlink Price Feed smart contract by address * @param _chainlinkContract Chainlink Price Feed smart contract address */ function setChainlinkContract(AggregatorV3Interface _chainlinkContract) external onlyOwner { EthPriceFeed = _chainlinkContract; emit CampaignStatsChanged(); } /** * @notice Owner can set the token conversion rate. Receiver tokens = tradeTokens * tokenRate * @param _token address of token to query token exchange rate */ function setErc20TokenConversionRate(IERC20 _token, uint256 _rate) external onlyOwner { require( erc20TokenConversionRate[_token] != _rate, "ICO_CAMPAIGN::RATE_INVALID" ); erc20TokenConversionRate[_token] = _rate; emit AllowTokenToTradeWithRate(address(_token), _rate); emit CampaignStatsChanged(); } /** * @notice Owner can set the release time (time in seconds) for claim functionality. * @param _releaseTime Value in uint256 determine when we allow claim to function */ function setReleaseTime(uint256 _releaseTime) external onlyOwner() { require(_releaseTime >= block.timestamp, "ICO_CAMPAIGN::INVALID_TIME"); require( _releaseTime >= closeTime, "ICO_CAMPAIGN::INVALID_TIME_COMPATIBILITY" ); releaseTime = _releaseTime; emit CampaignStatsChanged(); } /** * @notice Owner can set the close time (time in seconds). User can buy before close time. * @param _closeTime Value in uint256 determine when we stop user to by tokens */ function setCloseTime(uint256 _closeTime) external onlyOwner() { require(_closeTime >= block.timestamp, "ICO_CAMPAIGN::INVALID_TIME"); closeTime = _closeTime; emit CampaignStatsChanged(); } /** * @notice Owner can set the open time (time in seconds). User can buy after open time. * @param _openTime Value in uint256 determine when we allow user to by tokens */ function setOpenTime(uint256 _openTime) external onlyOwner() { openTime = _openTime; emit CampaignStatsChanged(); } /** * @notice User can buy token by this function when available. tokens = wei * etherConversionRate / 10 ** etherConversionRateDecimals * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokenByEther(address _beneficiary) public payable whenNotPaused nonReentrant { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); require(_validPurchase(), "ICO_CAMPAIGN::ENDED"); // calculate token amount to be created uint256 tokens = _getEtherToTokenAmount(weiAmount); require( tokenSoldMapping[_beneficiary] + tokens <= etherConversionRate .mul(1 ether) .mul(100000000000) .div(getLatestEthPrice()) .div(10**etherConversionRateDecimals), "ICO_CAMPAIGN::MAX_1000_USD_TOTAL" ); uint256 platformFee = _payPlatformEtherFee(); _forwardFunds(weiAmount.sub(platformFee)); _updatePurchasingState(_beneficiary, weiAmount, tokens); emit TokenPurchaseByEther(msg.sender, _beneficiary, weiAmount, tokens); } /** * @notice Calculate the tokens user can receive. Receive User's trade tokens and transfer tokens * @dev tokens = _token * token Conversion Rate Of _token * @param _beneficiary Address performing the token purchase * @param _token Address of willing to exchange to ke performing the token purchase * @param _amount Value of amount will exchange of tokens */ function buyTokenByToken( address _beneficiary, IERC20 _token, uint256 _amount ) public whenNotPaused nonReentrant { require(_token != IERC20(address(0)), "ICO_CAMPAIGN::TOKEN_ADDRESS_0"); require(_token != token, "ICO_CAMPAIGN::TOKEN_INVALID"); require(_validPurchase(), "ICO_CAMPAIGN::ENDED"); _preValidatePurchase(_beneficiary, _amount); require( getErc20TokenConversionRate(_token) != 0, "ICO_CAMPAIGN::TOKEN_NOT_ALLOWED" ); IERC20 tradeToken = _token; uint256 allowance = tradeToken.allowance(msg.sender, address(this)); require(allowance >= _amount, "ICO_CAMPAIGN::TOKEN_NOT_APPROVED"); uint256 tokens = _getTokenToTokenAmount(_token, _amount); require( tokenSoldMapping[_beneficiary] + tokens <= erc20TokenConversionRate[_token] .mul(1 ether) .mul(100000000000) .div(getLatestEthPrice()), "ICO_CAMPAIGN::MAX_1000_USD_TOTAL" ); uint256 platformFee = _payPlatformTokenFee(_token, _amount); _forwardTokenFunds(_token, _amount.sub(platformFee)); _updatePurchasingState(_beneficiary, 0, tokens); emit TokenPurchaseByToken( msg.sender, _beneficiary, address(_token), _amount, tokens ); } function claimTokens() public whenNotPaused nonReentrant { require(isClaimable(), "ICO_CAMPAIGN::ICO_NOT_ENDED"); uint256 amount = tokenSoldMapping[msg.sender]; require(amount > 0, "ICO_CAMPAIGN::EMPTY_BALANCE"); token.transfer(msg.sender, amount); _updateDeliveryState(msg.sender, amount); emit TokenClaimed(msg.sender, amount); } /** * @notice Return true if campaign has ended * @dev User cannot purchase / trade tokens when isFinalized == true * @return true if the ICO ended. */ function isFinalized() public view returns (bool) { return block.timestamp >= closeTime; } /** * @notice Return true if campaign has ended and is eneable to claim * @dev User cannot claim tokens when isClaimable == false * @return true if the release time < now. */ function isClaimable() public view returns (bool) { return block.timestamp >= releaseTime; } /** * @notice Return true if campaign is open * @dev User can purchase / trade tokens when isOpen == true * @return true if the ICO is open. */ function isOpen() public view returns (bool) { return (block.timestamp < closeTime) && (block.timestamp > openTime); } /** * @notice Owner can receive their remaining tokens when ICO Ended * @dev Can refund remainning token if the ico ended * @param _wallet Address wallet who receive the remainning tokens when Ico end * @param _amount Value of amount will exchange of tokens */ function refundTokenForIcoOwner(address _wallet, uint256 _amount) external onlyOwner { require(isClaimable(), "ICO_CAMPAIGN::ICO_NOT_ENDED"); require(getAvailableTokens() > 0, "ICO_CAMPAIGN::EMPTY_BALANCE"); _deliverTokens(_wallet, _amount); emit RefundedTokenForIcoWhenEndIco(_wallet, _amount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure { require( _beneficiary != address(0), "ICO_CAMPAIGN::INVALID_BENEFICIARY" ); require(_weiAmount != 0, "ICO_CAMPAIGN::INVALID_WEI_AMOUNT"); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getEtherToTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 rate = getEtherConversionRate(); return _weiAmount.mul(rate).div(10**etherConversionRateDecimals); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _token Address of exchange token * @param _amount Value of exchange tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenToTokenAmount(IERC20 _token, uint256 _amount) internal view returns (uint256) { uint256 rate = getErc20TokenConversionRate(_token); return _amount.mul(rate); } /** * @dev Source of tokens. Transfer / mint * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds(uint256 _value) internal { address payable wallet = address(uint160(fundingWallet)); (bool success, ) = wallet.call{value: _value}(""); require(success, "ICO_CAMPAIGN::WALLET_TRANSFER_FAILED"); } /** * @dev Determines how Token is stored/forwarded on purchases. */ function _forwardTokenFunds(IERC20 _token, uint256 _amount) internal { _token.transferFrom(msg.sender, fundingWallet, _amount); } /** * @param _beneficiary Address performing the token purchase * @param _tokenAmount Value of sold tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { require(getAvailableTokens() >= _tokenAmount, "ICO_CAMPAIGN::TOKEN_NOT_ENOUGH"); weiRaised = weiRaised.add(_weiAmount); tokenSold = tokenSold.add(_tokenAmount); tokenSoldMapping[_beneficiary] = tokenSoldMapping[_beneficiary].add( _tokenAmount ); } /** * @param _beneficiary Address performing the token delivery * @param _tokenAmount Value of delivery tokens */ function _updateDeliveryState(address _beneficiary, uint256 _tokenAmount) internal { tokenClaimed = tokenClaimed.add(_tokenAmount); tokenSoldMapping[_beneficiary] = tokenSoldMapping[_beneficiary].sub( _tokenAmount ); } // @return true if the transaction can buy tokens function _validPurchase() internal view returns (bool) { bool withinPeriod = block.timestamp >= openTime && block.timestamp <= closeTime; return withinPeriod; } /** * @notice Pay platform fee when a trade executed in eth * @dev Only pay when use Lemonade to register ICO Campaign */ function _payPlatformEtherFee() private returns (uint256) { address payable platformRevenueAddress = address(uint160(_getPlatformRevenueAddress())); uint256 platformFeeRate = _getPlatformFeeRate(); uint256 payment = msg.value; uint256 platformFee = payment.mul(platformFeeRate).div(100); (bool success, ) = platformRevenueAddress.call{value: platformFee}(""); require(success, "ICO_CAMPAIGN::PAY_PLATFORM_FEE_FAILED"); return platformFee; } /** * @notice Pay platform fee when a trade executed in tokens * @dev Only pay when use Lemonade to register ICO Campaign */ function _payPlatformTokenFee(IERC20 _token, uint256 _amount) private returns (uint256) { address payable platformRevenueAddress = address(uint160(_getPlatformRevenueAddress())); uint256 platformFeeRate = _getPlatformFeeRate(); uint256 payment = _amount; uint256 platformFee = payment.mul(platformFeeRate).div(100); _token.transferFrom(msg.sender, platformRevenueAddress, platformFee); return platformFee; } /** * @notice Call to factory contract to get Platform Fee * @dev return a fixed number fee of Platform */ function _getPlatformFeeRate() private view returns (uint256) { return ICampaignFactory(factory).getPlatformFeeRate(); } /** * @notice Call to factory contract to get revenue address * @dev return address of factory vault */ function _getPlatformRevenueAddress() private view returns (address) { return ICampaignFactory(factory).getplatformRevenueAddress(); } /** * @dev Transfer eth to an address * @param _to Address receiving the eth * @param _amount Amount of wei to transfer */ function _transfer(address _to, uint256 _amount) private { address payable payableAddress = address(uint160(_to)); (bool success, ) = payableAddress.call{value: _amount}(""); require(success, "ICO_CAMPAIGN::TRANSFER_FEE_FAILED"); } /** * @dev Transfer token to an address * @param _to Address receiving the eth * @param _amount Amount of wei to transfer */ function _transferToken( IERC20 _token, address _to, uint256 _amount ) private { _token.transferFrom(msg.sender, _to, _amount); } }
* @param _beneficiary Address performing the token purchase @param _tokenAmount Value of sold tokens @param _weiAmount Value in wei involved in the purchase/
function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { require(getAvailableTokens() >= _tokenAmount, "ICO_CAMPAIGN::TOKEN_NOT_ENOUGH"); weiRaised = weiRaised.add(_weiAmount); tokenSold = tokenSold.add(_tokenAmount); tokenSoldMapping[_beneficiary] = tokenSoldMapping[_beneficiary].add( _tokenAmount ); }
14,656,560
[ 1, 67, 70, 4009, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 225, 389, 2316, 6275, 1445, 434, 272, 1673, 2430, 225, 389, 1814, 77, 6275, 1445, 316, 732, 77, 24589, 316, 326, 23701, 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, 389, 2725, 10262, 343, 11730, 1119, 12, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 1814, 77, 6275, 16, 203, 3639, 2254, 5034, 389, 2316, 6275, 203, 565, 262, 2713, 288, 203, 3639, 2583, 12, 588, 5268, 5157, 1435, 1545, 389, 2316, 6275, 16, 315, 2871, 51, 67, 39, 2192, 4066, 10452, 2866, 8412, 67, 4400, 67, 1157, 26556, 16715, 8863, 203, 3639, 732, 77, 12649, 5918, 273, 732, 77, 12649, 5918, 18, 1289, 24899, 1814, 77, 6275, 1769, 203, 3639, 1147, 55, 1673, 273, 1147, 55, 1673, 18, 1289, 24899, 2316, 6275, 1769, 203, 3639, 1147, 55, 1673, 3233, 63, 67, 70, 4009, 74, 14463, 814, 65, 273, 1147, 55, 1673, 3233, 63, 67, 70, 4009, 74, 14463, 814, 8009, 1289, 12, 203, 5411, 389, 2316, 6275, 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 ]
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract UserManager { struct User { string username; bytes32 hashToProfilePicture; bool exists; } uint public numberOfUsers; mapping(string => bool) internal usernameExists; mapping(address => User) public addressToUser; mapping(bytes32 => bool) public profilePictureExists; mapping(string => address) internal usernameToAddress; event NewUser(address indexed user, string username, bytes32 profilePicture); function register(string _username, bytes32 _hashToProfilePicture) public { require(usernameExists[_username] == false || keccak256(abi.encodePacked(getUsername(msg.sender))) == keccak256(abi.encodePacked(_username)) ); if (usernameExists[getUsername(msg.sender)]) { // if he already had username, that username is free now usernameExists[getUsername(msg.sender)] = false; } else { numberOfUsers++; emit NewUser(msg.sender, _username, _hashToProfilePicture); } addressToUser[msg.sender] = User({ username: _username, hashToProfilePicture: _hashToProfilePicture, exists: true }); usernameExists[_username] = true; profilePictureExists[_hashToProfilePicture] = true; usernameToAddress[_username] = msg.sender; } function changeProfilePicture(bytes32 _hashToProfilePicture) public { require(addressToUser[msg.sender].exists, "User doesn't exists"); addressToUser[msg.sender].hashToProfilePicture = _hashToProfilePicture; } function getUserInfo(address _address) public view returns(string, bytes32) { User memory user = addressToUser[_address]; return (user.username, user.hashToProfilePicture); } function getUsername(address _address) public view returns(string) { return addressToUser[_address].username; } function getProfilePicture(address _address) public view returns(bytes32) { return addressToUser[_address].hashToProfilePicture; } function isUsernameExists(string _username) public view returns(bool) { return usernameExists[_username]; } } contract AssetManager is Ownable { struct Asset { uint id; uint packId; /// atributes field is going to be 3 digit uint where every digit can be "1" or "2" /// 1st digit will tell us if asset is background 1 - true / 2 - false /// 2nd digit will tell us if rotation is enabled 1 - true / 2 - false /// 3rd digit will tell us if scaling is enabled 1 - true / 2 - false uint attributes; bytes32 ipfsHash; // image } struct AssetPack { bytes32 packCover; uint[] assetIds; address creator; uint price; string ipfsHash; // containing title and description } uint public numberOfAssets; uint public numberOfAssetPacks; Asset[] public assets; AssetPack[] public assetPacks; UserManager public userManager; mapping(address => uint) public artistBalance; mapping(bytes32 => bool) public hashExists; mapping(address => uint[]) public createdAssetPacks; mapping(address => uint[]) public boughtAssetPacks; mapping(address => mapping(uint => bool)) public hasPermission; mapping(uint => address) public approvedTakeover; event AssetPackCreated(uint indexed id, address indexed owner); event AssetPackBought(uint indexed id, address indexed buyer); function addUserManager(address _userManager) public onlyOwner { require(userManager == address(0)); userManager = UserManager(_userManager); } /// @notice Function to create assetpack /// @param _packCover is cover image for asset pack /// @param _attributes is array of attributes /// @param _ipfsHashes is array containing all ipfsHashes for assets we'd like to put in pack /// @param _packPrice is price for total assetPack (every asset will have average price) /// @param _ipfsHash ipfs hash containing title and description in json format function createAssetPack( bytes32 _packCover, uint[] _attributes, bytes32[] _ipfsHashes, uint _packPrice, string _ipfsHash) public { require(_ipfsHashes.length > 0); require(_ipfsHashes.length < 50); require(_attributes.length == _ipfsHashes.length); uint[] memory ids = new uint[](_ipfsHashes.length); for (uint i = 0; i < _ipfsHashes.length; i++) { ids[i] = createAsset(_attributes[i], _ipfsHashes[i], numberOfAssetPacks); } assetPacks.push(AssetPack({ packCover: _packCover, assetIds: ids, creator: msg.sender, price: _packPrice, ipfsHash: _ipfsHash })); createdAssetPacks[msg.sender].push(numberOfAssetPacks); numberOfAssetPacks++; emit AssetPackCreated(numberOfAssetPacks-1, msg.sender); } /// @notice Function which creates an asset /// @param _attributes is meta info for asset /// @param _ipfsHash is ipfsHash to image of asset function createAsset(uint _attributes, bytes32 _ipfsHash, uint _packId) internal returns(uint) { uint id = numberOfAssets; require(isAttributesValid(_attributes), "Attributes are not valid."); assets.push(Asset({ id : id, packId: _packId, attributes: _attributes, ipfsHash : _ipfsHash })); numberOfAssets++; return id; } /// @notice Method to buy right to use specific asset pack /// @param _to is address of user who will get right on that asset pack /// @param _assetPackId is id of asset pack user is buying function buyAssetPack(address _to, uint _assetPackId) public payable { require(!checkHasPermissionForPack(_to, _assetPackId)); AssetPack memory assetPack = assetPacks[_assetPackId]; require(msg.value >= assetPack.price); // if someone wants to pay more money for asset pack, we will give all of it to creator artistBalance[assetPack.creator] += msg.value * 95 / 100; artistBalance[owner] += msg.value * 5 / 100; boughtAssetPacks[_to].push(_assetPackId); hasPermission[_to][_assetPackId] = true; emit AssetPackBought(_assetPackId, _to); } /// @notice Change price of asset pack /// @param _assetPackId is id of asset pack for changing price /// @param _newPrice is new price for that asset pack function changeAssetPackPrice(uint _assetPackId, uint _newPrice) public { require(assetPacks[_assetPackId].creator == msg.sender); assetPacks[_assetPackId].price = _newPrice; } /// @notice Approve address to become creator of that pack /// @param _assetPackId id of asset pack for other address to claim /// @param _newCreator address that will be able to claim that asset pack function approveTakeover(uint _assetPackId, address _newCreator) public { require(assetPacks[_assetPackId].creator == msg.sender); approvedTakeover[_assetPackId] = _newCreator; } /// @notice claim asset pack that is previously approved by creator /// @param _assetPackId id of asset pack that is changing creator function claimAssetPack(uint _assetPackId) public { require(approvedTakeover[_assetPackId] == msg.sender); approvedTakeover[_assetPackId] = address(0); assetPacks[_assetPackId].creator = msg.sender; } ///@notice Function where all artists can withdraw their funds function withdraw() public { uint amount = artistBalance[msg.sender]; artistBalance[msg.sender] = 0; msg.sender.transfer(amount); } /// @notice Function to fetch total number of assets /// @return numberOfAssets function getNumberOfAssets() public view returns (uint) { return numberOfAssets; } /// @notice Function to fetch total number of assetpacks /// @return uint numberOfAssetPacks function getNumberOfAssetPacks() public view returns(uint) { return numberOfAssetPacks; } /// @notice Function to check if user have permission (owner / bought) for pack /// @param _address is address of user /// @param _packId is id of pack function checkHasPermissionForPack(address _address, uint _packId) public view returns (bool) { return (assetPacks[_packId].creator == _address) || hasPermission[_address][_packId]; } /// @notice Function to check does hash exist in mapping /// @param _ipfsHash is bytes32 representation of hash function checkHashExists(bytes32 _ipfsHash) public view returns (bool) { return hashExists[_ipfsHash]; } /// @notice method that gets all unique packs from array of assets function pickUniquePacks(uint[] assetIds) public view returns (uint[]) { require(assetIds.length > 0); uint[] memory packs = new uint[](assetIds.length); uint packsCount = 0; for (uint i = 0; i < assetIds.length; i++) { Asset memory asset = assets[assetIds[i]]; bool exists = false; for (uint j = 0; j < packsCount; j++) { if (asset.packId == packs[j]) { exists = true; } } if (!exists) { packs[packsCount] = asset.packId; packsCount++; } } uint[] memory finalPacks = new uint[](packsCount); for (i = 0; i < packsCount; i++) { finalPacks[i] = packs[i]; } return finalPacks; } /// @notice Method to get all info for an asset /// @param id is id of asset /// @return All data for an asset function getAssetInfo(uint id) public view returns (uint, uint, uint, bytes32) { require(id >= 0); require(id < numberOfAssets); Asset memory asset = assets[id]; return (asset.id, asset.packId, asset.attributes, asset.ipfsHash); } /// @notice method returns all asset packs created by _address /// @param _address is creator address function getAssetPacksUserCreated(address _address) public view returns(uint[]) { return createdAssetPacks[_address]; } /// @notice Function to get ipfsHash for selected asset /// @param _id is id of asset we'd like to get ipfs hash /// @return string representation of ipfs hash of that asset function getAssetIpfs(uint _id) public view returns (bytes32) { require(_id < numberOfAssets); return assets[_id].ipfsHash; } /// @notice Function to get attributes for selected asset /// @param _id is id of asset we'd like to get ipfs hash /// @return uint representation of attributes of that asset function getAssetAttributes(uint _id) public view returns (uint) { require(_id < numberOfAssets); return assets[_id].attributes; } /// @notice Function to get array of ipfsHashes for specific assets /// @dev need for data parsing on frontend efficiently /// @param _ids is array of ids /// @return bytes32 array of hashes function getIpfsForAssets(uint[] _ids) public view returns (bytes32[]) { bytes32[] memory hashes = new bytes32[](_ids.length); for (uint i = 0; i < _ids.length; i++) { Asset memory asset = assets[_ids[i]]; hashes[i] = asset.ipfsHash; } return hashes; } /// @notice method that returns attributes for many assets function getAttributesForAssets(uint[] _ids) public view returns(uint[]) { uint[] memory attributes = new uint[](_ids.length); for (uint i = 0; i < _ids.length; i++) { Asset memory asset = assets[_ids[i]]; attributes[i] = asset.attributes; } return attributes; } /// @notice Function to get ipfs hash and id for all assets in one asset pack /// @param _assetPackId is id of asset pack /// @return two arrays with data function getAssetPackData(uint _assetPackId) public view returns(bytes32, address, uint, uint[], uint[], bytes32[], string, string, bytes32) { require(_assetPackId < numberOfAssetPacks); AssetPack memory assetPack = assetPacks[_assetPackId]; bytes32[] memory hashes = new bytes32[](assetPack.assetIds.length); for (uint i = 0; i < assetPack.assetIds.length; i++) { hashes[i] = getAssetIpfs(assetPack.assetIds[i]); } uint[] memory attributes = getAttributesForAssets(assetPack.assetIds); return( assetPack.packCover, assetPack.creator, assetPack.price, assetPack.assetIds, attributes, hashes, assetPack.ipfsHash, userManager.getUsername(assetPack.creator), userManager.getProfilePicture(assetPack.creator) ); } function getAssetPackPrice(uint _assetPackId) public view returns (uint) { require(_assetPackId < numberOfAssetPacks); return assetPacks[_assetPackId].price; } function getBoughtAssetPacks(address _address) public view returns (uint[]) { return boughtAssetPacks[_address]; } /// @notice Function to get cover image for every assetpack /// @param _packIds is array of asset pack ids /// @return bytes32[] array of hashes function getCoversForPacks(uint[] _packIds) public view returns (bytes32[]) { require(_packIds.length > 0); bytes32[] memory covers = new bytes32[](_packIds.length); for (uint i = 0; i < _packIds.length; i++) { AssetPack memory assetPack = assetPacks[_packIds[i]]; covers[i] = assetPack.packCover; } return covers; } function isAttributesValid(uint attributes) private pure returns(bool) { if (attributes < 100 || attributes > 999) { return false; } uint num = attributes; while (num > 0) { if (num % 10 != 1 && num % 10 != 2) { return false; } num = num / 10; } return true; } }
@notice Function to get ipfsHash for selected asset @param _id is id of asset we'd like to get ipfs hash @return string representation of ipfs hash of that asset
function getAssetIpfs(uint _id) public view returns (bytes32) { require(_id < numberOfAssets); return assets[_id].ipfsHash; }
900,619
[ 1, 2083, 358, 336, 2359, 2556, 2310, 364, 3170, 3310, 225, 389, 350, 353, 612, 434, 3310, 732, 14271, 3007, 358, 336, 2359, 2556, 1651, 327, 533, 4335, 434, 2359, 2556, 1651, 434, 716, 3310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 24689, 5273, 2556, 12, 11890, 389, 350, 13, 1071, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 2583, 24899, 350, 411, 7922, 10726, 1769, 203, 540, 203, 3639, 327, 7176, 63, 67, 350, 8009, 625, 2556, 2310, 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 ]
pragma solidity 0.5.6; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } contract Ownable { address payable public owner; /** * @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); _; } function transferOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract GameWave is ERC20, ERC20Detailed, Ownable { uint paymentsTime = block.timestamp; uint totalPaymentAmount; uint lastTotalPaymentAmount; uint minted = 20000000; mapping (address => uint256) lastWithdrawTime; /** * @dev The GW constructor sets the original variables * specified in the contract ERC20Detailed. */ constructor() public ERC20Detailed("Game wave token", "GWT", 18) { _mint(msg.sender, minted * (10 ** uint256(decimals()))); } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract. */ function () payable external { if (msg.value == 0){ withdrawDividends(msg.sender); } } /** * @notice This function allows the investor to see the amount of dividends available for withdrawal. * @param _holder this is the address of the investor, where you can see the number of diverders available for withdrawal. * @return An uint the value available for the removal of dividends. */ function getDividends(address _holder) view public returns(uint) { if (paymentsTime >= lastWithdrawTime[_holder]){ return totalPaymentAmount.mul(balanceOf(_holder)).div(minted * (10 ** uint256(decimals()))); } else { return 0; } } /** * @notice This function allows the investor to withdraw dividends available for withdrawal. * @param _holder this is the address of the investor, by which there is a withdrawal available to dividend. * @return An uint value of removed dividends. */ function withdrawDividends(address payable _holder) public returns(uint) { uint dividends = getDividends(_holder); lastWithdrawTime[_holder] = block.timestamp; lastTotalPaymentAmount = lastTotalPaymentAmount.add(dividends); _holder.transfer(dividends); } /** * @notice This function initializes payments with a period of 30 days. * */ function startPayments() public { require(block.timestamp >= paymentsTime + 30 days); owner.transfer(totalPaymentAmount.sub(lastTotalPaymentAmount)); totalPaymentAmount = address(this).balance; paymentsTime = block.timestamp; lastTotalPaymentAmount = 0; } } /* * @title Bank * @dev Bank contract which contained all ETH from Bears and Bulls teams. * When time in blockchain will be grater then current deadline or last deadline need call getWinner function * then participants able get prizes. * * Last participant(last hero) win 10% from all bank * * - To get prize send 0 ETH to this contract */ contract Bank is Ownable { using SafeMath for uint256; mapping (uint256 => mapping (address => uint256)) public depositBears; mapping (uint256 => mapping (address => uint256)) public depositBulls; uint256 public currentDeadline; uint256 public currentRound = 1; uint256 public lastDeadline; uint256 public defaultCurrentDeadlineInHours = 24; uint256 public defaultLastDeadlineInHours = 48; uint256 public countOfBears; uint256 public countOfBulls; uint256 public totalSupplyOfBulls; uint256 public totalSupplyOfBears; uint256 public totalGWSupplyOfBulls; uint256 public totalGWSupplyOfBears; uint256 public probabilityOfBulls; uint256 public probabilityOfBears; address public lastHero; address public lastHeroHistory; uint256 public jackPot; uint256 public winner; uint256 public withdrawn; uint256 public withdrawnGW; uint256 public remainder; uint256 public remainderGW; uint256 public rate = 1; uint256 public rateModifier = 0; uint256 public tokenReturn; address crowdSale; uint256 public lastTotalSupplyOfBulls; uint256 public lastTotalSupplyOfBears; uint256 public lastTotalGWSupplyOfBulls; uint256 public lastTotalGWSupplyOfBears; uint256 public lastProbabilityOfBulls; uint256 public lastProbabilityOfBears; address public lastRoundHero; uint256 public lastJackPot; uint256 public lastWinner; uint256 public lastBalance; uint256 public lastBalanceGW; uint256 public lastCountOfBears; uint256 public lastCountOfBulls; uint256 public lastWithdrawn; uint256 public lastWithdrawnGW; bool public finished = false; Bears public BearsContract; Bulls public BullsContract; GameWave public GameWaveContract; /* * @dev Constructor create first deadline */ constructor(address _crowdSale) public { _setRoundTime(6, 8); crowdSale = _crowdSale; } /** * @dev Setter token rate. * @param _rate this value for change percent relation rate to count of tokens. * @param _rateModifier this value for change math operation under tokens. */ function setRateToken(uint256 _rate, uint256 _rateModifier) public onlyOwner returns(uint256){ rate = _rate; rateModifier = _rateModifier; } /** * @dev Setter crowd sale address. * @param _crowdSale Address of the crowd sale contract. */ function setCrowdSale(address _crowdSale) public onlyOwner{ crowdSale = _crowdSale; } /** * @dev Setter round time. * @param _currentDeadlineInHours this value current deadline in hours. * @param _lastDeadlineInHours this value last deadline in hours. */ function _setRoundTime(uint _currentDeadlineInHours, uint _lastDeadlineInHours) internal { defaultCurrentDeadlineInHours = _currentDeadlineInHours; defaultLastDeadlineInHours = _lastDeadlineInHours; currentDeadline = block.timestamp + 60 * 60 * _currentDeadlineInHours; lastDeadline = block.timestamp + 60 * 60 * _lastDeadlineInHours; } /** * @dev Setter round time. * @param _currentDeadlineInHours this value current deadline in hours. * @param _lastDeadlineInHours this value last deadline in hours. */ function setRoundTime(uint _currentDeadlineInHours, uint _lastDeadlineInHours) public onlyOwner { _setRoundTime(_currentDeadlineInHours, _lastDeadlineInHours); } /** * @dev Setter the GameWave contract address. Address can be set at once. * @param _GameWaveAddress Address of the GameWave contract */ function setGameWaveAddress(address payable _GameWaveAddress) public { require(address(GameWaveContract) == address(0x0)); GameWaveContract = GameWave(_GameWaveAddress); } /** * @dev Setter the Bears contract address. Address can be set at once. * @param _bearsAddress Address of the Bears contract */ function setBearsAddress(address payable _bearsAddress) external { require(address(BearsContract) == address(0x0)); BearsContract = Bears(_bearsAddress); } /** * @dev Setter the Bulls contract address. Address can be set at once. * @param _bullsAddress Address of the Bulls contract */ function setBullsAddress(address payable _bullsAddress) external { require(address(BullsContract) == address(0x0)); BullsContract = Bulls(_bullsAddress); } /** * @dev Getting time from blockchain for timer */ function getNow() view public returns(uint){ return block.timestamp; } /** * @dev Getting state of game. True - game continue, False - game stopped */ function getState() view public returns(bool) { if (block.timestamp > currentDeadline) { return false; } return true; } /** * @dev Setting info about participant from Bears or Bulls contract * @param _lastHero Address of participant * @param _deposit Amount of deposit */ function setInfo(address _lastHero, uint256 _deposit) public { require(address(BearsContract) == msg.sender || address(BullsContract) == msg.sender); if (address(BearsContract) == msg.sender) { require(depositBulls[currentRound][_lastHero] == 0, "You are already in bulls team"); if (depositBears[currentRound][_lastHero] == 0) countOfBears++; totalSupplyOfBears = totalSupplyOfBears.add(_deposit.mul(90).div(100)); depositBears[currentRound][_lastHero] = depositBears[currentRound][_lastHero].add(_deposit.mul(90).div(100)); } if (address(BullsContract) == msg.sender) { require(depositBears[currentRound][_lastHero] == 0, "You are already in bears team"); if (depositBulls[currentRound][_lastHero] == 0) countOfBulls++; totalSupplyOfBulls = totalSupplyOfBulls.add(_deposit.mul(90).div(100)); depositBulls[currentRound][_lastHero] = depositBulls[currentRound][_lastHero].add(_deposit.mul(90).div(100)); } lastHero = _lastHero; if (currentDeadline.add(120) <= lastDeadline) { currentDeadline = currentDeadline.add(120); } else { currentDeadline = lastDeadline; } jackPot += _deposit.mul(10).div(100); calculateProbability(); } function estimateTokenPercent(uint256 _difference) public view returns(uint256){ if (rateModifier == 0) { return _difference.mul(rate); } else { return _difference.div(rate); } } /** * @dev Calculation probability for team's win */ function calculateProbability() public { require(winner == 0 && getState()); totalGWSupplyOfBulls = GameWaveContract.balanceOf(address(BullsContract)); totalGWSupplyOfBears = GameWaveContract.balanceOf(address(BearsContract)); uint256 percent = (totalSupplyOfBulls.add(totalSupplyOfBears)).div(100); if (totalGWSupplyOfBulls < 1 ether) { totalGWSupplyOfBulls = 0; } if (totalGWSupplyOfBears < 1 ether) { totalGWSupplyOfBears = 0; } if (totalGWSupplyOfBulls <= totalGWSupplyOfBears) { uint256 difference = totalGWSupplyOfBears.sub(totalGWSupplyOfBulls).div(0.01 ether); probabilityOfBears = totalSupplyOfBears.mul(100).div(percent).add(estimateTokenPercent(difference)); if (probabilityOfBears > 8000) { probabilityOfBears = 8000; } if (probabilityOfBears < 2000) { probabilityOfBears = 2000; } probabilityOfBulls = 10000 - probabilityOfBears; } else { uint256 difference = totalGWSupplyOfBulls.sub(totalGWSupplyOfBears).div(0.01 ether); probabilityOfBulls = totalSupplyOfBulls.mul(100).div(percent).add(estimateTokenPercent(difference)); if (probabilityOfBulls > 8000) { probabilityOfBulls = 8000; } if (probabilityOfBulls < 2000) { probabilityOfBulls = 2000; } probabilityOfBears = 10000 - probabilityOfBulls; } totalGWSupplyOfBulls = GameWaveContract.balanceOf(address(BullsContract)); totalGWSupplyOfBears = GameWaveContract.balanceOf(address(BearsContract)); } /** * @dev Getting winner team */ function getWinners() public { require(winner == 0 && !getState()); uint256 seed1 = address(this).balance; uint256 seed2 = totalSupplyOfBulls; uint256 seed3 = totalSupplyOfBears; uint256 seed4 = totalGWSupplyOfBulls; uint256 seed5 = totalGWSupplyOfBulls; uint256 seed6 = block.difficulty; uint256 seed7 = block.timestamp; bytes32 randomHash = keccak256(abi.encodePacked(seed1, seed2, seed3, seed4, seed5, seed6, seed7)); uint randomNumber = uint(randomHash); if (randomNumber == 0){ randomNumber = 1; } uint winningNumber = randomNumber % 10000; if (1 <= winningNumber && winningNumber <= probabilityOfBears){ winner = 1; } if (probabilityOfBears < winningNumber && winningNumber <= 10000){ winner = 2; } if (GameWaveContract.balanceOf(address(BullsContract)) > 0) GameWaveContract.transferFrom( address(BullsContract), address(this), GameWaveContract.balanceOf(address(BullsContract)) ); if (GameWaveContract.balanceOf(address(BearsContract)) > 0) GameWaveContract.transferFrom( address(BearsContract), address(this), GameWaveContract.balanceOf(address(BearsContract)) ); lastTotalSupplyOfBulls = totalSupplyOfBulls; lastTotalSupplyOfBears = totalSupplyOfBears; lastTotalGWSupplyOfBears = totalGWSupplyOfBears; lastTotalGWSupplyOfBulls = totalGWSupplyOfBulls; lastRoundHero = lastHero; lastJackPot = jackPot; lastWinner = winner; lastCountOfBears = countOfBears; lastCountOfBulls = countOfBulls; lastWithdrawn = withdrawn; lastWithdrawnGW = withdrawnGW; if (lastBalance > lastWithdrawn){ remainder = lastBalance.sub(lastWithdrawn); address(GameWaveContract).transfer(remainder); } lastBalance = lastTotalSupplyOfBears.add(lastTotalSupplyOfBulls).add(lastJackPot); if (lastBalanceGW > lastWithdrawnGW){ remainderGW = lastBalanceGW.sub(lastWithdrawnGW); tokenReturn = (totalGWSupplyOfBears.add(totalGWSupplyOfBulls)).mul(20).div(100).add(remainderGW); GameWaveContract.transfer(crowdSale, tokenReturn); } lastBalanceGW = GameWaveContract.balanceOf(address(this)); totalSupplyOfBulls = 0; totalSupplyOfBears = 0; totalGWSupplyOfBulls = 0; totalGWSupplyOfBears = 0; remainder = 0; remainderGW = 0; jackPot = 0; withdrawn = 0; winner = 0; withdrawnGW = 0; countOfBears = 0; countOfBulls = 0; probabilityOfBulls = 0; probabilityOfBears = 0; _setRoundTime(defaultCurrentDeadlineInHours, defaultLastDeadlineInHours); currentRound++; } /** * @dev Payable function for take prize */ function () external payable { if (msg.value == 0){ require(depositBears[currentRound - 1][msg.sender] > 0 || depositBulls[currentRound - 1][msg.sender] > 0); uint payout = 0; uint payoutGW = 0; if (lastWinner == 1 && depositBears[currentRound - 1][msg.sender] > 0) { payout = calculateLastETHPrize(msg.sender); } if (lastWinner == 2 && depositBulls[currentRound - 1][msg.sender] > 0) { payout = calculateLastETHPrize(msg.sender); } if (payout > 0) { depositBears[currentRound - 1][msg.sender] = 0; depositBulls[currentRound - 1][msg.sender] = 0; withdrawn = withdrawn.add(payout); msg.sender.transfer(payout); } if ((lastWinner == 1 && depositBears[currentRound - 1][msg.sender] == 0) || (lastWinner == 2 && depositBulls[currentRound - 1][msg.sender] == 0)) { payoutGW = calculateLastGWPrize(msg.sender); withdrawnGW = withdrawnGW.add(payoutGW); GameWaveContract.transfer(msg.sender, payoutGW); } if (msg.sender == lastRoundHero) { lastHeroHistory = lastRoundHero; lastRoundHero = address(0x0); withdrawn = withdrawn.add(lastJackPot); msg.sender.transfer(lastJackPot); } } } /** * @dev Getting ETH prize of participant * @param participant Address of participant */ function calculateETHPrize(address participant) public view returns(uint) { uint payout = 0; uint256 totalSupply = (totalSupplyOfBears.add(totalSupplyOfBulls)); if (depositBears[currentRound][participant] > 0) { payout = totalSupply.mul(depositBears[currentRound][participant]).div(totalSupplyOfBears); } if (depositBulls[currentRound][participant] > 0) { payout = totalSupply.mul(depositBulls[currentRound][participant]).div(totalSupplyOfBulls); } return payout; } /** * @dev Getting GW Token prize of participant * @param participant Address of participant */ function calculateGWPrize(address participant) public view returns(uint) { uint payout = 0; uint totalSupply = (totalGWSupplyOfBears.add(totalGWSupplyOfBulls)).mul(80).div(100); if (depositBears[currentRound][participant] > 0) { payout = totalSupply.mul(depositBears[currentRound][participant]).div(totalSupplyOfBears); } if (depositBulls[currentRound][participant] > 0) { payout = totalSupply.mul(depositBulls[currentRound][participant]).div(totalSupplyOfBulls); } return payout; } /** * @dev Getting ETH prize of _lastParticipant * @param _lastParticipant Address of _lastParticipant */ function calculateLastETHPrize(address _lastParticipant) public view returns(uint) { uint payout = 0; uint256 totalSupply = (lastTotalSupplyOfBears.add(lastTotalSupplyOfBulls)); if (depositBears[currentRound - 1][_lastParticipant] > 0) { payout = totalSupply.mul(depositBears[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBears); } if (depositBulls[currentRound - 1][_lastParticipant] > 0) { payout = totalSupply.mul(depositBulls[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBulls); } return payout; } /** * @dev Getting GW Token prize of _lastParticipant * @param _lastParticipant Address of _lastParticipant */ function calculateLastGWPrize(address _lastParticipant) public view returns(uint) { uint payout = 0; uint totalSupply = (lastTotalGWSupplyOfBears.add(lastTotalGWSupplyOfBulls)).mul(80).div(100); if (depositBears[currentRound - 1][_lastParticipant] > 0) { payout = totalSupply.mul(depositBears[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBears); } if (depositBulls[currentRound - 1][_lastParticipant] > 0) { payout = totalSupply.mul(depositBulls[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBulls); } return payout; } } /** * @dev Base contract for teams */ contract CryptoTeam { using SafeMath for uint256; //Developers fund address payable public owner; Bank public BankContract; GameWave public GameWaveContract; constructor() public { owner = msg.sender; } /** * @dev Payable function. 10% will send to Developers fund and 90% will send to JackPot contract. * Also setting info about player. */ function () external payable { require(BankContract.getState() && msg.value >= 0.05 ether); BankContract.setInfo(msg.sender, msg.value.mul(90).div(100)); owner.transfer(msg.value.mul(10).div(100)); address(BankContract).transfer(msg.value.mul(90).div(100)); } } /* * @dev Bears contract. To play game with Bears send ETH to this contract */ contract Bears is CryptoTeam { constructor(address payable _bankAddress, address payable _GameWaveAddress) public { BankContract = Bank(_bankAddress); BankContract.setBearsAddress(address(this)); GameWaveContract = GameWave(_GameWaveAddress); GameWaveContract.approve(_bankAddress, 9999999999999999999000000000000000000); } } /* * @dev Bulls contract. To play game with Bulls send ETH to this contract */ contract Bulls is CryptoTeam { constructor(address payable _bankAddress, address payable _GameWaveAddress) public { BankContract = Bank(_bankAddress); BankContract.setBullsAddress(address(this)); GameWaveContract = GameWave(_GameWaveAddress); GameWaveContract.approve(_bankAddress, 9999999999999999999000000000000000000); } } /* * @dev Crowdsal contract */ contract Sale { GameWave public GWContract; uint256 public buyPrice; address public owner; uint balance; bool crowdSaleClosed = false; constructor( address payable _GWContract ) payable public { owner = msg.sender; GWContract = GameWave(_GWContract); GWContract.approve(owner, 9999999999999999999000000000000000000); } /** * @notice Allow users to buy tokens for `newBuyPrice` * @param newBuyPrice Price users can buy from the contract. */ function setPrice(uint256 newBuyPrice) public { buyPrice = newBuyPrice; } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract and * sends tokens to the buyer. */ function () payable external { uint amount = msg.value; balance = (amount / buyPrice) * 10 ** 18; GWContract.transfer(msg.sender, balance); address(GWContract).transfer(amount); } }
* @title Standard ERC20 token @dev Implementation of the basic standard token./
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom( address from, address to, uint256 value ) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } }
13,116,653
[ 1, 8336, 4232, 39, 3462, 1147, 225, 25379, 434, 326, 5337, 4529, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 353, 467, 654, 39, 3462, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 8151, 31, 203, 203, 225, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 225, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 4963, 3088, 1283, 31, 203, 225, 289, 203, 203, 225, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 70, 26488, 63, 8443, 15533, 203, 225, 289, 203, 203, 225, 445, 1699, 1359, 12, 203, 565, 1758, 3410, 16, 203, 565, 1758, 17571, 264, 203, 225, 262, 203, 225, 1071, 203, 225, 1476, 203, 225, 1135, 261, 11890, 5034, 13, 203, 225, 288, 203, 565, 327, 389, 8151, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 225, 289, 203, 203, 225, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 389, 13866, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 10019, 203, 203, 565, 389, 8151, 63, 3576, 18, 15330, 2 ]
./partial_match/1/0x5175d77a142813E54548f75d00Ccb7B7935FeaC9/sources/offerToken.sol
mint offeror designated initial amount of offerToken
_mint(offeror, _init);
15,993,628
[ 1, 81, 474, 10067, 280, 25264, 2172, 3844, 434, 10067, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 81, 474, 12, 23322, 280, 16, 389, 2738, 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 ]
./partial_match/1/0x235b25f9f56B39eFD8293C0d2A9Ee70719E25B85/sources/src/ButtonswapPair.sol
* @inheritdoc IButtonswapPair/
function setMaxVolatilityBps(uint16 newMaxVolatilityBps) external onlyFactory { maxVolatilityBps = newMaxVolatilityBps; emit MaxVolatilityBpsUpdated(newMaxVolatilityBps); }
4,108,390
[ 1, 36, 10093, 467, 3616, 22270, 4154, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10851, 17431, 30139, 38, 1121, 12, 11890, 2313, 394, 2747, 17431, 30139, 38, 1121, 13, 3903, 1338, 1733, 288, 203, 3639, 943, 17431, 30139, 38, 1121, 273, 394, 2747, 17431, 30139, 38, 1121, 31, 203, 3639, 3626, 4238, 17431, 30139, 38, 1121, 7381, 12, 2704, 2747, 17431, 30139, 38, 1121, 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 ]
pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV6Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin removes a market event MarketRemoved(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when a new COMP speed is set for a contributor event ContributorCompSpeedUpdated(address indexed contributor, uint newSpeed); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when COMP is granted by admin event CompGranted(address recipient, uint amount); /// @notice Emitted when B.Protocol is changed event NewBProtocol(address indexed cToken, address oldBProtocol, address newBProtocol); /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { // Set admin to Hundred deployer admin = 0x1001009911e3FE1d5B45FF8Efea7732C33a6C012; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving // Disabled for borrowers return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving // Disabled for borrowers return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } /* Only B.Protocol can liquidate */ address bLiquidator = bprotocol[address(cTokenBorrowed)]; if(bLiquidator != address(0) && IBProtocol(bLiquidator).canLiquidate(cTokenBorrowed, cTokenCollateral, repayAmount)) { require(liquidator == bLiquidator, "only B.Protocol can liquidate"); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower); distributeSupplierComp(cTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src); distributeSupplierComp(cToken, dst); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken // Note that isComped is not in active use anymore markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } function _disableMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (!markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken require(CToken(cToken).totalBorrowsCurrent() == 0, "market has borrows"); require(CToken(cToken).totalSupply() == 0, "market has supply"); _removeMarketInternal(address(cToken)); emit MarketRemoved(cToken); return uint(Error.NO_ERROR); } function _removeMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { if (allMarkets[i] == CToken(cToken)) { allMarkets[i] = allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } delete markets[cToken]; } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == implementation; } /*** Comp Distribution ***/ /** * @notice Set COMP speed for a single market * @param cToken The market whose COMP speed to update * @param compSpeed New COMP speed for market */ function setCompSpeedInternal(CToken cToken, uint compSpeed) internal { uint currentCompSpeed = compSpeeds[address(cToken)]; if (currentCompSpeed != 0) { // note that COMP speed could be set to 0 to halt liquidity rewards for a market updateCompSupplyIndex(address(cToken)); } else if (compSpeed != 0) { // Add the COMP market Market storage market = markets[address(cToken)]; require(market.isListed == true, "comp market is not listed"); if (compSupplyState[address(cToken)].index == 0 && compSupplyState[address(cToken)].block == 0) { compSupplyState[address(cToken)] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[address(cToken)].index == 0 && compBorrowState[address(cToken)].block == 0) { compBorrowState[address(cToken)] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentCompSpeed != compSpeed) { compSpeeds[address(cToken)] = compSpeed; emit CompSpeedUpdated(cToken, compSpeed); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ 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 Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = supplierAccrued; emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate additional accrued COMP for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint compSpeed = compContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && compSpeed > 0) { uint newAccrued = mul_(deltaBlocks, compSpeed); uint contributorAccrued = add_(compAccrued[contributor], newAccrued); compAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address[] memory holders, CToken[] memory cTokens) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j]); compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]); } } } /** * @notice Transfer COMP to the user * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param amount The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function grantCompInternal(address user, uint amount) internal returns (uint) { IERC20 comp = IERC20(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (amount > 0 && amount <= compRemaining) { comp.transfer(user, amount); return 0; } return amount; } /*** Comp Distribution Admin ***/ /** * @notice Transfer COMP to the recipient * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param recipient The address of the recipient to transfer COMP to * @param amount The amount of COMP to (possibly) transfer */ function _grantComp(address recipient, uint amount) public { require(adminOrInitializing(), "only admin can grant comp"); uint amountLeft = grantCompInternal(recipient, amount); require(amountLeft == 0, "insufficient comp for grant"); emit CompGranted(recipient, amount); } /** * @notice Set COMP speed for a single market * @param cToken The market whose COMP speed to update * @param compSpeed New COMP speed for market */ function _setCompSpeed(CToken cToken, uint compSpeed) public { require(adminOrInitializing(), "only admin can set comp speed"); setCompSpeedInternal(cToken, compSpeed); } /** * @notice Set COMP speed for a single contributor * @param contributor The contributor whose COMP speed to update * @param compSpeed New COMP speed for contributor */ function _setContributorCompSpeed(address contributor, uint compSpeed) public { require(adminOrInitializing(), "only admin can set comp speed"); // note that COMP speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (compSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } else { lastContributorBlock[contributor] = getBlockNumber(); } compContributorSpeeds[contributor] = compSpeed; emit ContributorCompSpeedUpdated(contributor, compSpeed); } function _setBProtocol(address cToken, address newBProtocol) public returns (uint) { require(adminOrInitializing(), "only admin can set B.Protocol"); emit NewBProtocol(cToken, bprotocol[cToken], newBProtocol); bprotocol[cToken] = newBProtocol; return uint(Error.NO_ERROR); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public pure returns (address) { return 0x10010078a54396F62c96dF8532dc2B4847d47ED3; } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * 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, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle.sol"; import "./IBProtocol.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public implementation; /** * @notice Pending brains of Unitroller */ address public pendingImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage { /// @notice The portion of COMP that each contributor receives per block mapping(address => uint) public compContributorSpeeds; /// @notice Last block at which a contributor's COMP rewards have been allocated mapping(address => uint) public lastContributorBlock; } contract ComptrollerV6Storage is ComptrollerV5Storage { /// @notice CToken => IBProtocol (per CToken debt) mapping(address => address) public bprotocol; } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `implementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to Hundred Deployer admin = 0x1001009911e3FE1d5B45FF8Efea7732C33a6C012; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingImplementation; pendingImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingImplementation || pendingImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = implementation; address oldPendingImplementation = pendingImplementation; implementation = pendingImplementation; pendingImplementation = address(0); emit NewImplementation(oldImplementation, implementation); emit NewPendingImplementation(oldPendingImplementation, pendingImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./EIP20NonStandardInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); function sweepToken(EIP20NonStandardInterface token) external; /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; /** * @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 { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { 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, uint scalar, uint addend) pure internal returns (uint) { 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) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } pragma solidity ^0.5.16; interface IBProtocol { function canLiquidate( address cTokenBorrowed, address cTokenCollateral, uint repayAmount ) external view returns(bool); }
Only B.Protocol can liquidate */
address bLiquidator = bprotocol[address(cTokenBorrowed)];
5,814,361
[ 1, 3386, 605, 18, 5752, 848, 4501, 26595, 340, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 324, 48, 18988, 350, 639, 273, 324, 8373, 63, 2867, 12, 71, 1345, 38, 15318, 329, 13, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 // solhint-disable-next-line compiler-version 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 IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./ModuleMapConsumer.sol"; import "../interfaces/IKernel.sol"; abstract contract Controlled is Initializable, ModuleMapConsumer { // controller address => is a controller mapping(address => bool) internal _controllers; address[] public controllers; function __Controlled_init(address[] memory controllers_, address moduleMap_) public initializer { for (uint256 i; i < controllers_.length; i++) { _controllers[controllers_[i]] = true; } controllers = controllers_; __ModuleMapConsumer_init(moduleMap_); } function addController(address controller) external onlyOwner { _controllers[controller] = true; bool added; for (uint256 i; i < controllers.length; i++) { if (controller == controllers[i]) { added = true; } } if (!added) { controllers.push(controller); } } modifier onlyOwner() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isOwner(msg.sender), "Controlled::onlyOwner: Caller is not owner" ); _; } modifier onlyManager() { require( IKernel(moduleMap.getModuleAddress(Modules.Kernel)).isManager(msg.sender), "Controlled::onlyManager: Caller is not manager" ); _; } modifier onlyController() { require( _controllers[msg.sender], "Controlled::onlyController: Caller is not controller" ); _; } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IModuleMap.sol"; abstract contract ModuleMapConsumer is Initializable { IModuleMap public moduleMap; function __ModuleMapConsumer_init(address moduleMap_) internal initializer { moduleMap = IModuleMap(moduleMap_); } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../interfaces/IIntegrationMap.sol"; import "../interfaces/IIntegration.sol"; import "../interfaces/IEtherRewards.sol"; import "../interfaces/IYieldManager.sol"; import "../interfaces/IUniswapTrader.sol"; import "../interfaces/ISushiSwapTrader.sol"; import "../interfaces/IUserPositions.sol"; import "../interfaces/IWeth9.sol"; import "../interfaces/IStrategyMap.sol"; import "./Controlled.sol"; import "./ModuleMapConsumer.sol"; /// @title Yield Manager /// @notice Manages yield deployments, harvesting, processing, and distribution contract YieldManager is Initializable, ModuleMapConsumer, Controlled, IYieldManager { using SafeERC20Upgradeable for IERC20MetadataUpgradeable; uint256 private gasAccountTargetEthBalance; uint32 private biosBuyBackEthWeight; uint32 private treasuryEthWeight; uint32 private protocolFeeEthWeight; uint32 private rewardsEthWeight; uint256 private lastEthRewardsAmount; address payable private gasAccount; address payable private treasuryAccount; mapping(address => uint256) private processedWethByToken; receive() external payable {} /// @param controllers_ The addresses of the controlling contracts /// @param moduleMap_ Address of the Module Map /// @param gasAccountTargetEthBalance_ The target ETH balance of the gas account /// @param biosBuyBackEthWeight_ The relative weight of ETH to send to BIOS buy back /// @param treasuryEthWeight_ The relative weight of ETH to send to the treasury /// @param protocolFeeEthWeight_ The relative weight of ETH to send to protocol fee accrual /// @param rewardsEthWeight_ The relative weight of ETH to send to user rewards /// @param gasAccount_ The address of the account to send ETH to gas for executing bulk system functions /// @param treasuryAccount_ The address of the system treasury account function initialize( address[] memory controllers_, address moduleMap_, uint256 gasAccountTargetEthBalance_, uint32 biosBuyBackEthWeight_, uint32 treasuryEthWeight_, uint32 protocolFeeEthWeight_, uint32 rewardsEthWeight_, address payable gasAccount_, address payable treasuryAccount_ ) public initializer { __Controlled_init(controllers_, moduleMap_); __ModuleMapConsumer_init(moduleMap_); gasAccountTargetEthBalance = gasAccountTargetEthBalance_; biosBuyBackEthWeight = biosBuyBackEthWeight_; treasuryEthWeight = treasuryEthWeight_; protocolFeeEthWeight = protocolFeeEthWeight_; rewardsEthWeight = rewardsEthWeight_; gasAccount = gasAccount_; treasuryAccount = treasuryAccount_; } /// @param gasAccountTargetEthBalance_ The target ETH balance of the gas account function updateGasAccountTargetEthBalance(uint256 gasAccountTargetEthBalance_) external override onlyController { gasAccountTargetEthBalance = gasAccountTargetEthBalance_; } /// @param biosBuyBackEthWeight_ The relative weight of ETH to send to BIOS buy back /// @param treasuryEthWeight_ The relative weight of ETH to send to the treasury /// @param protocolFeeEthWeight_ The relative weight of ETH to send to protocol fee accrual /// @param rewardsEthWeight_ The relative weight of ETH to send to user rewards function updateEthDistributionWeights( uint32 biosBuyBackEthWeight_, uint32 treasuryEthWeight_, uint32 protocolFeeEthWeight_, uint32 rewardsEthWeight_ ) external override onlyController { biosBuyBackEthWeight = biosBuyBackEthWeight_; treasuryEthWeight = treasuryEthWeight_; protocolFeeEthWeight = protocolFeeEthWeight_; rewardsEthWeight = rewardsEthWeight_; } /// @param gasAccount_ The address of the account to send ETH to gas for executing bulk system functions function updateGasAccount(address payable gasAccount_) external override onlyController { gasAccount = gasAccount_; } /// @param treasuryAccount_ The address of the system treasury account function updateTreasuryAccount(address payable treasuryAccount_) external override onlyController { treasuryAccount = treasuryAccount_; } /// @notice Withdraws and then re-deploys tokens to integrations according to configured weights function rebalance() external override onlyController { _deploy(); } /// @notice Deploys all tokens to all integrations according to configured weights function deploy() external override onlyController { _deploy(); } function _deploy() internal { bool shouldRedeploy = _rebalance(); if (shouldRedeploy) { _rebalance(); } } function _rebalance() internal returns (bool redeploy) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); IStrategyMap strategyMap = IStrategyMap( moduleMap.getModuleAddress(Modules.StrategyMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); uint256 integrationCount = integrationMap.getIntegrationAddressesLength(); uint256 denominator = integrationMap.getReserveRatioDenominator(); for (uint256 i = 0; i < integrationCount; i++) { address integration = integrationMap.getIntegrationAddress(i); for (uint256 j = 0; j < tokenCount; j++) { address token = integrationMap.getTokenAddress(j); uint256 numerator = integrationMap.getTokenReserveRatioNumerator(token); uint256 grossAmountInvested = strategyMap.getExpectedBalance( integration, token ); uint256 desiredBalance = grossAmountInvested - _calculateReserveAmount(grossAmountInvested, numerator, denominator); uint256 actualBalance = IIntegration(integration).getBalance(token); if (desiredBalance > actualBalance) { // Underfunded, top up redeploy = true; uint256 shortage = desiredBalance - actualBalance; if ( IERC20MetadataUpgradeable(token).balanceOf( moduleMap.getModuleAddress(Modules.Kernel) ) >= shortage ) { uint256 balanceBefore = IERC20MetadataUpgradeable(token).balanceOf( integration ); IERC20MetadataUpgradeable(token).safeTransferFrom( moduleMap.getModuleAddress(Modules.Kernel), integration, shortage ); uint256 balanceAfter = IERC20MetadataUpgradeable(token).balanceOf( integration ); IIntegration(integration).deposit( token, balanceAfter - balanceBefore ); } } else if (actualBalance > desiredBalance) { // Overfunded, give it a haircut redeploy = true; IIntegration(integration).withdraw( token, actualBalance - desiredBalance ); } } IIntegration(integration).deploy(); } } function _calculateReserveAmount( uint256 amount, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return (amount * numerator) / denominator; } /// @notice Harvests available yield from all tokens and integrations function harvestYield() public override onlyController { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); uint256 integrationCount = integrationMap.getIntegrationAddressesLength(); for ( uint256 integrationId; integrationId < integrationCount; integrationId++ ) { IIntegration(integrationMap.getIntegrationAddress(integrationId)) .harvestYield(); } for (uint256 tokenId; tokenId < tokenCount; tokenId++) { IERC20MetadataUpgradeable token = IERC20MetadataUpgradeable( integrationMap.getTokenAddress(tokenId) ); uint256 tokenDesiredReserve = getDesiredReserveTokenBalance( address(token) ); uint256 tokenActualReserve = getReserveTokenBalance(address(token)); uint256 harvestedTokenAmount = token.balanceOf(address(this)); // Check if reserves need to be replenished if (tokenDesiredReserve > tokenActualReserve) { // Need to replenish reserves if (tokenDesiredReserve - tokenActualReserve <= harvestedTokenAmount) { // Need to send portion of harvested token to Kernel to replenish reserves token.safeTransfer( moduleMap.getModuleAddress(Modules.Kernel), tokenDesiredReserve - tokenActualReserve ); } else { // Need to send all of harvested token to Kernel to partially replenish reserves token.safeTransfer( moduleMap.getModuleAddress(Modules.Kernel), token.balanceOf(address(this)) ); } } } } /// @notice Swaps all harvested yield tokens for WETH function processYield() external override onlyController { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); IERC20MetadataUpgradeable weth = IERC20MetadataUpgradeable( integrationMap.getWethTokenAddress() ); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { IERC20MetadataUpgradeable token = IERC20MetadataUpgradeable( integrationMap.getTokenAddress(tokenId) ); if (token.balanceOf(address(this)) > 0) { uint256 wethReceived; if (address(token) != address(weth)) { // If token is not WETH, need to swap it for WETH uint256 wethBalanceBefore = weth.balanceOf(address(this)); // Swap token harvested yield for WETH. If trade succeeds, update accounting. Otherwise, do not update accounting token.safeTransfer( moduleMap.getModuleAddress(Modules.UniswapTrader), token.balanceOf(address(this)) ); IUniswapTrader(moduleMap.getModuleAddress(Modules.UniswapTrader)) .swapExactInput( address(token), address(weth), address(this), token.balanceOf(moduleMap.getModuleAddress(Modules.UniswapTrader)) ); wethReceived = weth.balanceOf(address(this)) - wethBalanceBefore; } else { // If token is WETH, no swap is needed wethReceived = weth.balanceOf(address(this)) - getProcessedWethByTokenSum(); } // Update accounting processedWethByToken[address(token)] += wethReceived; } } } /// @notice Distributes ETH to the gas account, BIOS buy back, treasury, protocol fee accrual, and user rewards function distributeEth() external override onlyController { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address wethAddress = IIntegrationMap(integrationMap).getWethTokenAddress(); // First fill up gas wallet with ETH ethToGasAccount(); uint256 wethToDistribute = IERC20MetadataUpgradeable(wethAddress).balanceOf( address(this) ); if (wethToDistribute > 0) { uint256 biosBuyBackWethAmount = (wethToDistribute * biosBuyBackEthWeight) / getEthWeightSum(); uint256 treasuryWethAmount = (wethToDistribute * treasuryEthWeight) / getEthWeightSum(); uint256 protocolFeeWethAmount = (wethToDistribute * protocolFeeEthWeight) / getEthWeightSum(); uint256 rewardsWethAmount = wethToDistribute - biosBuyBackWethAmount - treasuryWethAmount - protocolFeeWethAmount; // Send WETH to SushiSwap trader for BIOS buy back IERC20MetadataUpgradeable(wethAddress).safeTransfer( moduleMap.getModuleAddress(Modules.SushiSwapTrader), biosBuyBackWethAmount ); // Swap WETH for ETH and transfer to the treasury account IWeth9(wethAddress).withdraw(treasuryWethAmount); payable(treasuryAccount).transfer(treasuryWethAmount); // Send ETH to protocol fee accrual rewards (BIOS stakers) ethToProtocolFeeAccrual(protocolFeeWethAmount); // Send ETH to token rewards ethToRewards(rewardsWethAmount); } } /// @notice Distributes WETH to gas wallet function ethToGasAccount() private { address wethAddress = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getWethTokenAddress(); uint256 wethBalance = IERC20MetadataUpgradeable(wethAddress).balanceOf( address(this) ); if (wethBalance > 0) { uint256 gasAccountActualEthBalance = gasAccount.balance; if (gasAccountActualEthBalance < gasAccountTargetEthBalance) { // Need to send ETH to gas account uint256 ethAmountToGasAccount; if ( wethBalance < gasAccountTargetEthBalance - gasAccountActualEthBalance ) { // Send all of WETH to gas wallet ethAmountToGasAccount = wethBalance; IWeth9(wethAddress).withdraw(ethAmountToGasAccount); gasAccount.transfer(ethAmountToGasAccount); } else { // Send portion of WETH to gas wallet ethAmountToGasAccount = gasAccountTargetEthBalance - gasAccountActualEthBalance; IWeth9(wethAddress).withdraw(ethAmountToGasAccount); gasAccount.transfer(ethAmountToGasAccount); } } } } /// @notice Uses any WETH held in the SushiSwap trader to buy back BIOS which is sent to the Kernel function biosBuyBack() external override onlyController { if ( IERC20MetadataUpgradeable( IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getWethTokenAddress() ).balanceOf(moduleMap.getModuleAddress(Modules.SushiSwapTrader)) > 0 ) { // Use all ETH sent to the SushiSwap trader to buy BIOS ISushiSwapTrader(moduleMap.getModuleAddress(Modules.SushiSwapTrader)) .biosBuyBack(); // Use all BIOS transferred to the Kernel to increase bios rewards IUserPositions(moduleMap.getModuleAddress(Modules.UserPositions)) .increaseBiosRewards(); } } /// @notice Distributes ETH to Rewards per token /// @param ethRewardsAmount The amount of ETH rewards to distribute function ethToRewards(uint256 ethRewardsAmount) private { uint256 processedWethByTokenSum = getProcessedWethSum(); require( processedWethByTokenSum > 0, "YieldManager::ethToRewards: No processed WETH to distribute" ); IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address wethAddress = integrationMap.getWethTokenAddress(); uint256 tokenCount = integrationMap.getTokenAddressesLength(); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { address tokenAddress = integrationMap.getTokenAddress(tokenId); if (processedWethByToken[tokenAddress] > 0) { IEtherRewards(moduleMap.getModuleAddress(Modules.EtherRewards)) .increaseEthRewards( tokenAddress, (ethRewardsAmount * processedWethByToken[tokenAddress]) / processedWethByTokenSum ); processedWethByToken[tokenAddress] = 0; } } lastEthRewardsAmount = ethRewardsAmount; IWeth9(wethAddress).withdraw(ethRewardsAmount); payable(moduleMap.getModuleAddress(Modules.Kernel)).transfer( ethRewardsAmount ); } /// @notice Distributes ETH to protocol fee accrual (BIOS staker rewards) /// @param protocolFeeEthRewardsAmount Amount of ETH to distribute to protocol fee accrual function ethToProtocolFeeAccrual(uint256 protocolFeeEthRewardsAmount) private { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); address biosAddress = integrationMap.getBiosTokenAddress(); address wethAddress = integrationMap.getWethTokenAddress(); if ( IStrategyMap(moduleMap.getModuleAddress(Modules.StrategyMap)) .getTokenTotalBalance(biosAddress) > 0 ) { // BIOS has been deposited, increase Ether rewards for BIOS depositors IEtherRewards(moduleMap.getModuleAddress(Modules.EtherRewards)) .increaseEthRewards(biosAddress, protocolFeeEthRewardsAmount); IWeth9(wethAddress).withdraw(protocolFeeEthRewardsAmount); payable(moduleMap.getModuleAddress(Modules.Kernel)).transfer( protocolFeeEthRewardsAmount ); } else { // No BIOS has been deposited, send WETH back to Kernel as reserves IERC20MetadataUpgradeable(wethAddress).transfer( moduleMap.getModuleAddress(Modules.Kernel), protocolFeeEthRewardsAmount ); } } /// @param tokenAddress The address of the token ERC20 contract /// @return harvestedTokenBalance The amount of the token yield harvested held in the Kernel function getHarvestedTokenBalance(address tokenAddress) external view override returns (uint256 harvestedTokenBalance) { if ( tokenAddress == IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getWethTokenAddress() ) { harvestedTokenBalance = IERC20MetadataUpgradeable(tokenAddress).balanceOf(address(this)) - getProcessedWethSum(); } else { harvestedTokenBalance = IERC20MetadataUpgradeable(tokenAddress).balanceOf( address(this) ); } } /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of the token held in the Kernel as reserves function getReserveTokenBalance(address tokenAddress) public view override returns (uint256) { require( IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getIsTokenAdded(tokenAddress), "YieldManager::getReserveTokenBalance: Token not added" ); return IERC20MetadataUpgradeable(tokenAddress).balanceOf( moduleMap.getModuleAddress(Modules.Kernel) ); } /// @param tokenAddress The address of the token ERC20 contract /// @return The desired amount of the token to hold in the Kernel as reserves function getDesiredReserveTokenBalance(address tokenAddress) public view override returns (uint256) { require( IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getIsTokenAdded(tokenAddress), "YieldManager::getDesiredReserveTokenBalance: Token not added" ); uint256 tokenReserveRatioNumerator = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getTokenReserveRatioNumerator(tokenAddress); uint256 tokenTotalBalance = IStrategyMap( moduleMap.getModuleAddress(Modules.StrategyMap) ).getTokenTotalBalance(tokenAddress); return (tokenTotalBalance * tokenReserveRatioNumerator) / IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap)) .getReserveRatioDenominator(); } /// @return ethWeightSum The sum of ETH distribution weights function getEthWeightSum() public view override returns (uint32 ethWeightSum) { ethWeightSum = biosBuyBackEthWeight + treasuryEthWeight + protocolFeeEthWeight + rewardsEthWeight; } /// @return processedWethSum The sum of yields processed into WETH function getProcessedWethSum() public view override returns (uint256 processedWethSum) { uint256 tokenCount = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getTokenAddressesLength(); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { address tokenAddress = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ).getTokenAddress(tokenId); processedWethSum += processedWethByToken[tokenAddress]; } } /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of WETH received from token yield processing function getProcessedWethByToken(address tokenAddress) public view override returns (uint256) { return processedWethByToken[tokenAddress]; } /// @return processedWethByTokenSum The sum of processed WETH function getProcessedWethByTokenSum() public view override returns (uint256 processedWethByTokenSum) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { processedWethByTokenSum += processedWethByToken[ integrationMap.getTokenAddress(tokenId) ]; } } /// @param tokenAddress The address of the token ERC20 contract /// @return tokenTotalIntegrationBalance The total amount of the token that can be withdrawn from integrations function getTokenTotalIntegrationBalance(address tokenAddress) public view override returns (uint256 tokenTotalIntegrationBalance) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 integrationCount = integrationMap.getIntegrationAddressesLength(); for ( uint256 integrationId; integrationId < integrationCount; integrationId++ ) { tokenTotalIntegrationBalance += IIntegration( integrationMap.getIntegrationAddress(integrationId) ).getBalance(tokenAddress); } } /// @return The address of the gas account function getGasAccount() public view override returns (address) { return gasAccount; } /// @return The address of the treasury account function getTreasuryAccount() public view override returns (address) { return treasuryAccount; } /// @return The last amount of ETH distributed to rewards function getLastEthRewardsAmount() public view override returns (uint256) { return lastEthRewardsAmount; } /// @return The target ETH balance of the gas account function getGasAccountTargetEthBalance() public view override returns (uint256) { return gasAccountTargetEthBalance; } /// @return The BIOS buyback ETH weight /// @return The Treasury ETH weight /// @return The Protocol fee ETH weight /// @return The rewards ETH weight function getEthDistributionWeights() public view override returns ( uint32, uint32, uint32, uint32 ) { return ( biosBuyBackEthWeight, treasuryEthWeight, protocolFeeEthWeight, rewardsEthWeight ); } } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IEtherRewards { /// @param token The address of the token ERC20 contract /// @param user The address of the user function updateUserRewards(address token, address user) external; /// @param token The address of the token ERC20 contract /// @param ethRewardsAmount The amount of Ether rewards to add function increaseEthRewards(address token, uint256 ethRewardsAmount) external; /// @param user The address of the user /// @return ethRewards The amount of Ether claimed function claimEthRewards(address user) external returns (uint256 ethRewards); /// @param token The address of the token ERC20 contract /// @param user The address of the user /// @return ethRewards The amount of Ether claimed function getUserTokenEthRewards(address token, address user) external view returns (uint256 ethRewards); /// @param user The address of the user /// @return ethRewards The amount of Ether claimed function getUserEthRewards(address user) external view returns (uint256 ethRewards); /// @param token The address of the token ERC20 contract /// @return The amount of Ether rewards for the specified token function getTokenEthRewards(address token) external view returns (uint256); /// @return The total value of ETH claimed by users function getTotalClaimedEthRewards() external view returns (uint256); /// @return The total value of ETH claimed by a user function getTotalUserClaimedEthRewards(address user) external view returns (uint256); /// @return The total amount of Ether rewards function getEthRewards() external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IIntegration { /// @param tokenAddress The address of the deposited token /// @param amount The amount of the token being deposited function deposit(address tokenAddress, uint256 amount) external; /// @param tokenAddress The address of the withdrawal token /// @param amount The amount of the token to withdraw function withdraw(address tokenAddress, uint256 amount) external; /// @dev Deploys all tokens held in the integration contract to the integrated protocol function deploy() external; /// @dev Harvests token yield from the Aave lending pool function harvestYield() external; /// @dev This returns the total amount of the underlying token that /// @dev has been deposited to the integration contract /// @param tokenAddress The address of the deployed token /// @return The amount of the underlying token that can be withdrawn function getBalance(address tokenAddress) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IIntegrationMap { struct Integration { bool added; string name; } struct Token { uint256 id; bool added; bool acceptingDeposits; bool acceptingWithdrawals; uint256 biosRewardWeight; uint256 reserveRatioNumerator; } /// @param contractAddress The address of the integration contract /// @param name The name of the protocol being integrated to function addIntegration(address contractAddress, string memory name) external; /// @param tokenAddress The address of the ERC20 token contract /// @param acceptingDeposits Whether token deposits are enabled /// @param acceptingWithdrawals Whether token withdrawals are enabled /// @param biosRewardWeight Token weight for BIOS rewards /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function addToken( address tokenAddress, bool acceptingDeposits, bool acceptingWithdrawals, uint256 biosRewardWeight, uint256 reserveRatioNumerator ) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenDeposits(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function enableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract function disableTokenWithdrawals(address tokenAddress) external; /// @param tokenAddress The address of the token ERC20 contract /// @param rewardWeight The updated token BIOS reward weight function updateTokenRewardWeight(address tokenAddress, uint256 rewardWeight) external; /// @param tokenAddress the address of the token ERC20 contract /// @param reserveRatioNumerator Number that gets divided by reserve ratio denominator to get reserve ratio function updateTokenReserveRatioNumerator( address tokenAddress, uint256 reserveRatioNumerator ) external; /// @param integrationId The ID of the integration /// @return The address of the integration contract function getIntegrationAddress(uint256 integrationId) external view returns (address); /// @param integrationAddress The address of the integration contract /// @return The name of the of the protocol being integrated to function getIntegrationName(address integrationAddress) external view returns (string memory); /// @return The address of the WETH token function getWethTokenAddress() external view returns (address); /// @return The address of the BIOS token function getBiosTokenAddress() external view returns (address); /// @param tokenId The ID of the token /// @return The address of the token ERC20 contract function getTokenAddress(uint256 tokenId) external view returns (address); /// @param tokenAddress The address of the token ERC20 contract /// @return The index of the token in the tokens array function getTokenId(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The token BIOS reward weight function getTokenBiosRewardWeight(address tokenAddress) external view returns (uint256); /// @return rewardWeightSum reward weight of depositable tokens function getBiosRewardWeightSum() external view returns (uint256 rewardWeightSum); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether depositing this token is currently enabled function getTokenAcceptingDeposits(address tokenAddress) external view returns (bool); /// @param tokenAddress The address of the token ERC20 contract /// @return bool indicating whether withdrawing this token is currently enabled function getTokenAcceptingWithdrawals(address tokenAddress) external view returns (bool); // @param tokenAddress The address of the token ERC20 contract // @return bool indicating whether the token has been added function getIsTokenAdded(address tokenAddress) external view returns (bool); // @param integrationAddress The address of the integration contract // @return bool indicating whether the integration has been added function getIsIntegrationAdded(address tokenAddress) external view returns (bool); /// @notice get the length of supported tokens /// @return The quantity of tokens added function getTokenAddressesLength() external view returns (uint256); /// @notice get the length of supported integrations /// @return The quantity of integrations added function getIntegrationAddressesLength() external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The value that gets divided by the reserve ratio denominator function getTokenReserveRatioNumerator(address tokenAddress) external view returns (uint256); /// @return The token reserve ratio denominator function getReserveRatioDenominator() external view returns (uint32); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IKernel { /// @param account The address of the account to check if they are a manager /// @return Bool indicating whether the account is a manger function isManager(address account) external view returns (bool); /// @param account The address of the account to check if they are an owner /// @return Bool indicating whether the account is an owner function isOwner(address account) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; enum Modules { Kernel, // 0 UserPositions, // 1 YieldManager, // 2 IntegrationMap, // 3 BiosRewards, // 4 EtherRewards, // 5 SushiSwapTrader, // 6 UniswapTrader, // 7 StrategyMap, // 8 StrategyManager // 9 } interface IModuleMap { function getModuleAddress(Modules key) external view returns (address); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; import "../interfaces/IIntegration.sol"; interface IStrategyMap { // #### Structs struct WeightedIntegration { address integration; uint256 weight; } struct Strategy { string name; uint256 totalStrategyWeight; mapping(address => bool) enabledTokens; address[] tokens; WeightedIntegration[] integrations; } struct StrategySummary { string name; uint256 totalStrategyWeight; address[] tokens; WeightedIntegration[] integrations; } struct StrategyTransaction { uint256 amount; address token; } // #### Events event NewStrategy( uint256 indexed id, string name, WeightedIntegration[] integrations, address[] tokens ); event UpdateName(uint256 indexed id, string name); event UpdateIntegrations( uint256 indexed id, WeightedIntegration[] integrations ); event UpdateTokens(uint256 indexed id, address[] tokens); event DeleteStrategy( uint256 indexed id, string name, address[] tokens, WeightedIntegration[] integrations ); event EnterStrategy( uint256 indexed id, address indexed user, address[] tokens, uint256[] amounts ); event ExitStrategy( uint256 indexed id, address indexed user, address[] tokens, uint256[] amounts ); // #### Functions /** @notice Adds a new strategy to the list of available strategies @param name the name of the new strategy @param integrations the integrations and weights that form the strategy */ function addStrategy( string calldata name, WeightedIntegration[] memory integrations, address[] calldata tokens ) external; /** @notice Updates the strategy name @param name the new name */ function updateName(uint256 id, string calldata name) external; /** @notice Updates a strategy's accepted tokens @param id The strategy ID @param tokens The new tokens to allow */ function updateTokens(uint256 id, address[] calldata tokens) external; /** @notice Updates the strategy integrations @param integrations the new integrations */ function updateIntegrations( uint256 id, WeightedIntegration[] memory integrations ) external; /** @notice Deletes a strategy @dev This can only be called successfully if the strategy being deleted doesn't have any assets invested in it @param id the strategy to delete */ function deleteStrategy(uint256 id) external; /** @notice Increases the amount of a set of tokens in a strategy @param id the strategy to deposit into @param tokens the tokens to deposit @param amounts The amounts to be deposited */ function enterStrategy( uint256 id, address user, address[] calldata tokens, uint256[] calldata amounts ) external; /** @notice Decreases the amount of a set of tokens invested in a strategy @param id the strategy to withdraw assets from @param tokens the tokens to withdraw @param amounts The amounts to be withdrawn */ function exitStrategy( uint256 id, address user, address[] calldata tokens, uint256[] calldata amounts ) external; /** @notice Getter function to return the nested arrays as well as the name @param id the strategy to return */ function getStrategy(uint256 id) external view returns (StrategySummary memory); /** @notice Returns the expected balance of a given token in a given integration @param integration the integration the amount should be invested in @param token the token that is being invested @return balance the balance of the token that should be currently invested in the integration */ function getExpectedBalance(address integration, address token) external view returns (uint256 balance); /** @notice Returns the amount of a given token currently invested in a strategy @param id the strategy id to check @param token The token to retrieve the balance for @return amount the amount of token that is invested in the strategy */ function getStrategyTokenBalance(uint256 id, address token) external view returns (uint256 amount); /** @notice returns the amount of a given token a user has invested in a given strategy @param id the strategy id @param token the token address @param user the user who holds the funds @return amount the amount of token that the user has invested in the strategy */ function getUserStrategyBalanceByToken( uint256 id, address token, address user ) external view returns (uint256 amount); /** @notice Returns the amount of a given token that a user has invested across all strategies @param token the token address @param user the user holding the funds @return amount the amount of tokens the user has invested across all strategies */ function getUserInvestedAmountByToken(address token, address user) external view returns (uint256 amount); /** @notice Returns the total amount of a token invested across all strategies @param token the token to fetch the balance for @return amount the amount of the token currently invested */ function getTokenTotalBalance(address token) external view returns (uint256 amount); /** @notice Returns the weight of an individual integration within the system @param integration the integration to look up @return The weight of the integration */ function getIntegrationWeight(address integration) external view returns (uint256); /** @notice Returns the sum of all weights in the system. @return The sum of all integration weights within the system */ function getIntegrationWeightSum() external view returns (uint256); /// @notice autogenerated getter definition function idCounter() external view returns(uint256); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface ISushiSwapTrader { /// @param slippageNumerator_ The number divided by the slippage denominator to get the slippage percentage function updateSlippageNumerator(uint24 slippageNumerator_) external; /// @notice Swaps all WETH held in this contract for BIOS and sends to the kernel /// @return Bool indicating whether the trade succeeded function biosBuyBack() external returns (bool); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address of the token out recipient /// @param amountIn The exact amount of the input to swap /// @param amountOutMin The minimum amount of tokenOut to receive from the swap /// @return bool Indicates whether the swap succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn, uint256 amountOutMin ) external returns (bool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IUniswapTrader { struct Path { address tokenOut; uint256 firstPoolFee; address tokenInTokenOut; uint256 secondPoolFee; address tokenIn; } /// @param tokenA The address of tokenA ERC20 contract /// @param tokenB The address of tokenB ERC20 contract /// @param fee The Uniswap pool fee /// @param slippageNumerator The value divided by the slippage denominator /// to calculate the allowable slippage function addPool( address tokenA, address tokenB, uint24 fee, uint24 slippageNumerator ) external; /// @param tokenA The address of tokenA of the pool /// @param tokenB The address of tokenB of the pool /// @param poolIndex The index of the pool for the specified token pair /// @param slippageNumerator The new slippage numerator to update the pool function updatePoolSlippageNumerator( address tokenA, address tokenB, uint256 poolIndex, uint24 slippageNumerator ) external; /// @notice Changes which Uniswap pool to use as the default pool /// @notice when swapping between token0 and token1 /// @param tokenA The address of tokenA of the pool /// @param tokenB The address of tokenB of the pool /// @param primaryPoolIndex The index of the Uniswap pool to make the new primary pool function updatePairPrimaryPool( address tokenA, address tokenB, uint256 primaryPoolIndex ) external; /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address to receive the tokens /// @param amountIn The exact amount of the input to swap /// @return tradeSuccess Indicates whether the trade succeeded function swapExactInput( address tokenIn, address tokenOut, address recipient, uint256 amountIn ) external returns (bool tradeSuccess); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param recipient The address to receive the tokens /// @param amountOut The exact amount of the output token to receive /// @return tradeSuccess Indicates whether the trade succeeded function swapExactOutput( address tokenIn, address tokenOut, address recipient, uint256 amountOut ) external returns (bool tradeSuccess); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountOut The exact amount of token being swapped for /// @return amountInMaximum The maximum amount of tokenIn to spend, factoring in allowable slippage function getAmountInMaximum( address tokenIn, address tokenOut, uint256 amountOut ) external view returns (uint256 amountInMaximum); /// @param tokenIn The address of the input token /// @param tokenOut The address of the output token /// @param amountIn The exact amount of the input to swap /// @return amountOut The estimated amount of tokenOut to receive function getEstimatedTokenOut( address tokenIn, address tokenOut, uint256 amountIn ) external view returns (uint256 amountOut); function getPathFor(address tokenOut, address tokenIn) external view returns (Path memory); function setPathFor( address tokenOut, address tokenIn, uint256 firstPoolFee, address tokenInTokenOut, uint256 secondPoolFee ) external; /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return token0 The address of the sorted token0 /// @return token1 The address of the sorted token1 function getTokensSorted(address tokenA, address tokenB) external pure returns (address token0, address token1); /// @return The number of token pairs configured function getTokenPairsLength() external view returns (uint256); /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return The quantity of pools configured for the specified token pair function getTokenPairPoolsLength(address tokenA, address tokenB) external view returns (uint256); /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @param poolId The index of the pool in the pools mapping /// @return feeNumerator The numerator that gets divided by the fee denominator function getPoolFeeNumerator( address tokenA, address tokenB, uint256 poolId ) external view returns (uint24 feeNumerator); function getPoolAddress(address tokenA, address tokenB) external view returns (address pool); } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IUserPositions { /// @param biosRewardsDuration_ The duration in seconds for a BIOS rewards period to last function setBiosRewardsDuration(uint32 biosRewardsDuration_) external; /// @param sender The account seeding BIOS rewards /// @param biosAmount The amount of BIOS to add to rewards function seedBiosRewards(address sender, uint256 biosAmount) external; /// @notice Sends all BIOS available in the Kernel to each token BIOS rewards pool based up configured weights function increaseBiosRewards() external; /// @notice User is allowed to deposit whitelisted tokens /// @param depositor Address of the account depositing /// @param tokens Array of token the token addresses /// @param amounts Array of token amounts /// @param ethAmount The amount of ETH sent with the deposit function deposit( address depositor, address[] memory tokens, uint256[] memory amounts, uint256 ethAmount ) external; /// @notice User is allowed to withdraw tokens /// @param recipient The address of the user withdrawing /// @param tokens Array of token the token addresses /// @param amounts Array of token amounts /// @param withdrawWethAsEth Boolean indicating whether should receive WETH balance as ETH function withdraw( address recipient, address[] memory tokens, uint256[] memory amounts, bool withdrawWethAsEth ) external returns (uint256 ethWithdrawn); /// @notice Allows a user to withdraw entire balances of the specified tokens and claim rewards /// @param recipient The address of the user withdrawing tokens /// @param tokens Array of token address that user is exiting positions from /// @param withdrawWethAsEth Boolean indicating whether should receive WETH balance as ETH /// @return tokenAmounts The amounts of each token being withdrawn /// @return ethWithdrawn The amount of ETH being withdrawn /// @return ethClaimed The amount of ETH being claimed from rewards /// @return biosClaimed The amount of BIOS being claimed from rewards function withdrawAllAndClaim( address recipient, address[] memory tokens, bool withdrawWethAsEth ) external returns ( uint256[] memory tokenAmounts, uint256 ethWithdrawn, uint256 ethClaimed, uint256 biosClaimed ); /// @param user The address of the user claiming ETH rewards function claimEthRewards(address user) external returns (uint256 ethClaimed); /// @notice Allows users to claim their BIOS rewards for each token /// @param recipient The address of the usuer claiming BIOS rewards function claimBiosRewards(address recipient) external returns (uint256 biosClaimed); /// @param asset Address of the ERC20 token contract /// @return The total balance of the asset deposited in the system function totalTokenBalance(address asset) external view returns (uint256); /// @param asset Address of the ERC20 token contract /// @param account Address of the user account function userTokenBalance(address asset, address account) external view returns (uint256); /// @return The Bios Rewards Duration function getBiosRewardsDuration() external view returns (uint32); /// @notice Transfers tokens to the StrategyMap /// @dev This is a ledger adjustment. The tokens remain in the kernel. /// @param recipient The user to transfer funds for /// @param tokens the tokens to be moved /// @param amounts the amounts of each token to move function transferToStrategy( address recipient, address[] memory tokens, uint256[] memory amounts ) external; /// @notice Transfers tokens from the StrategyMap /// @dev This is a ledger adjustment. The tokens remain in the kernel. /// @param recipient The user to transfer funds for /// @param tokens the tokens to be moved /// @param amounts the amounts of each token to move function transferFromStrategy( address recipient, address[] memory tokens, uint256[] memory amounts ) external; } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IWeth9 { event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); function deposit() external payable; /// @param wad The amount of wETH to withdraw into ETH function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.4; interface IYieldManager { /// @param gasAccountTargetEthBalance_ The target ETH balance of the gas account function updateGasAccountTargetEthBalance(uint256 gasAccountTargetEthBalance_) external; /// @param biosBuyBackEthWeight_ The relative weight of ETH to send to BIOS buy back /// @param treasuryEthWeight_ The relative weight of ETH to send to the treasury /// @param protocolFeeEthWeight_ The relative weight of ETH to send to protocol fee accrual /// @param rewardsEthWeight_ The relative weight of ETH to send to user rewards function updateEthDistributionWeights( uint32 biosBuyBackEthWeight_, uint32 treasuryEthWeight_, uint32 protocolFeeEthWeight_, uint32 rewardsEthWeight_ ) external; /// @param gasAccount_ The address of the account to send ETH to gas for executing bulk system functions function updateGasAccount(address payable gasAccount_) external; /// @param treasuryAccount_ The address of the system treasury account function updateTreasuryAccount(address payable treasuryAccount_) external; /// @notice Withdraws and then re-deploys tokens to integrations according to configured weights function rebalance() external; /// @notice Deploys all tokens to all integrations according to configured weights function deploy() external; /// @notice Harvests available yield from all tokens and integrations function harvestYield() external; /// @notice Swaps harvested yield for all tokens for ETH function processYield() external; /// @notice Distributes ETH to the gas account, BIOS buy back, treasury, protocol fee accrual, and user rewards function distributeEth() external; /// @notice Uses WETH to buy back BIOS which is sent to the Kernel function biosBuyBack() external; /// @param tokenAddress The address of the token ERC20 contract /// @return harvestedTokenBalance The amount of the token yield harvested held in the Kernel function getHarvestedTokenBalance(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of the token held in the Kernel as reserves function getReserveTokenBalance(address tokenAddress) external view returns (uint256); /// @param tokenAddress The address of the token ERC20 contract /// @return The desired amount of the token to hold in the Kernel as reserves function getDesiredReserveTokenBalance(address tokenAddress) external view returns (uint256); /// @return ethWeightSum The sum of ETH distribution weights function getEthWeightSum() external view returns (uint32 ethWeightSum); /// @return processedWethSum The sum of yields processed into WETH function getProcessedWethSum() external view returns (uint256 processedWethSum); /// @param tokenAddress The address of the token ERC20 contract /// @return The amount of WETH received from token yield processing function getProcessedWethByToken(address tokenAddress) external view returns (uint256); /// @return processedWethByTokenSum The sum of processed WETH function getProcessedWethByTokenSum() external view returns (uint256 processedWethByTokenSum); /// @param tokenAddress The address of the token ERC20 contract /// @return tokenTotalIntegrationBalance The total amount of the token that can be withdrawn from integrations function getTokenTotalIntegrationBalance(address tokenAddress) external view returns (uint256 tokenTotalIntegrationBalance); /// @return The address of the gas account function getGasAccount() external view returns (address); /// @return The address of the treasury account function getTreasuryAccount() external view returns (address); /// @return The last amount of ETH distributed to rewards function getLastEthRewardsAmount() external view returns (uint256); /// @return The target ETH balance of the gas account function getGasAccountTargetEthBalance() external view returns (uint256); /// @return The BIOS buyback ETH weight /// @return The Treasury ETH weight /// @return The Protocol fee ETH weight /// @return The rewards ETH weight function getEthDistributionWeights() external view returns ( uint32, uint32, uint32, uint32 ); }
@return processedWethByTokenSum The sum of processed WETH
function getProcessedWethByTokenSum() public view override returns (uint256 processedWethByTokenSum) { IIntegrationMap integrationMap = IIntegrationMap( moduleMap.getModuleAddress(Modules.IntegrationMap) ); uint256 tokenCount = integrationMap.getTokenAddressesLength(); for (uint256 tokenId; tokenId < tokenCount; tokenId++) { processedWethByTokenSum += processedWethByToken[ integrationMap.getTokenAddress(tokenId) ]; } }
13,875,916
[ 1, 2463, 5204, 59, 546, 858, 1345, 3495, 1021, 2142, 434, 5204, 678, 1584, 44, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 3570, 3692, 59, 546, 858, 1345, 3495, 1435, 203, 565, 1071, 203, 565, 1476, 203, 565, 3849, 203, 565, 1135, 261, 11890, 5034, 5204, 59, 546, 858, 1345, 3495, 13, 203, 225, 288, 203, 565, 467, 15372, 863, 12040, 863, 273, 467, 15372, 863, 12, 203, 1377, 1605, 863, 18, 588, 3120, 1887, 12, 7782, 18, 15372, 863, 13, 203, 565, 11272, 203, 565, 2254, 5034, 1147, 1380, 273, 12040, 863, 18, 588, 1345, 7148, 1782, 5621, 203, 203, 565, 364, 261, 11890, 5034, 1147, 548, 31, 1147, 548, 411, 1147, 1380, 31, 1147, 548, 27245, 288, 203, 1377, 5204, 59, 546, 858, 1345, 3495, 1011, 5204, 59, 546, 858, 1345, 63, 203, 3639, 12040, 863, 18, 588, 1345, 1887, 12, 2316, 548, 13, 203, 1377, 308, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-19 */ //SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // ________ _______ // / ____/ /__ ____ ____ _ / ____(_)___ ____ _____ ________ // / __/ / / _ \/ __ \/ __ `/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ // / /___/ / __/ / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/ // /_____/_/\___/_/ /_/\__,_(_)_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ // // ==================================================================== // ====================== Elena Protocol (USE) ======================== // ==================================================================== // Dapp : https://elena.finance // Twitter : https://twitter.com/ElenaProtocol // Telegram: https://t.me/ElenaFinance // ==================================================================== // File: contracts\@openzeppelin\contracts\math\SafeMath.sol // License: MIT /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts\@openzeppelin\contracts\token\ERC20\IERC20.sol // License: MIT /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\@openzeppelin\contracts\utils\EnumerableSet.sol // License: MIT /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts\@openzeppelin\contracts\utils\Address.sol // License: MIT /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts\@openzeppelin\contracts\GSN\Context.sol // License: MIT /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts\@openzeppelin\contracts\access\AccessControl.sol // License: MIT /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts\Common\ContractGuard.sol // License: MIT contract ContractGuard { mapping(uint256 => mapping(address => bool)) private _status; function checkSameOriginReentranted() internal view returns (bool) { return _status[block.number][tx.origin]; } function checkSameSenderReentranted() internal view returns (bool) { return _status[block.number][msg.sender]; } modifier onlyOneBlock() { require( !checkSameOriginReentranted(), 'ContractGuard: one block, one function' ); require( !checkSameSenderReentranted(), 'ContractGuard: one block, one function' ); _; _status[block.number][tx.origin] = true; _status[block.number][msg.sender] = true; } } // File: contracts\Common\IERC20Detail.sol // License: MIT interface IERC20Detail is IERC20 { function decimals() external view returns (uint8); } // File: contracts\Share\IShareToken.sol // License: MIT interface IShareToken is IERC20 { function pool_mint(address m_address, uint256 m_amount) external; function pool_burn_from(address b_address, uint256 b_amount) external; function burn(uint256 amount) external; } // File: contracts\Oracle\IUniswapPairOracle.sol // License: MIT // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period interface IUniswapPairOracle { function getPairToken(address token) external view returns(address); function containsToken(address token) external view returns(bool); function getSwapTokenReserve(address token) external view returns(uint256); function update() external returns(bool); // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut); } // File: contracts\USE\IUSEStablecoin.sol // License: MIT interface IUSEStablecoin { 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); function owner_address() external returns (address); function creator_address() external returns (address); function timelock_address() external returns (address); function genesis_supply() external returns (uint256); function refresh_cooldown() external returns (uint256); function price_target() external returns (uint256); function price_band() external returns (uint256); function DEFAULT_ADMIN_ADDRESS() external returns (address); function COLLATERAL_RATIO_PAUSER() external returns (bytes32); function collateral_ratio_paused() external returns (bool); function last_call_time() external returns (uint256); function USEDAIOracle() external returns (IUniswapPairOracle); function USESharesOracle() external returns (IUniswapPairOracle); /* ========== VIEWS ========== */ function use_pools(address a) external view returns (bool); function global_collateral_ratio() external view returns (uint256); function use_price() external view returns (uint256); function share_price() external view returns (uint256); function share_price_in_use() external view returns (uint256); function globalCollateralValue() external view returns (uint256); /* ========== PUBLIC FUNCTIONS ========== */ function refreshCollateralRatio() external; function swapCollateralAmount() external view returns(uint256); function pool_mint(address m_address, uint256 m_amount) external; function pool_burn_from(address b_address, uint256 b_amount) external; function burn(uint256 amount) external; } // File: contracts\USE\Pools\USEPoolAlgo.sol // License: MIT contract USEPoolAlgo { using SafeMath for uint256; // Constants for various precisions uint256 public constant PRICE_PRECISION = 1e6; uint256 public constant COLLATERAL_RATIO_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFU_Params { uint256 shares_price_usd; uint256 col_price_usd; uint256 shares_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackShares_Params { uint256 excess_collateral_dollar_value_d18; uint256 shares_price_usd; uint256 col_price_usd; uint256 shares_amount; } // ================ Functions ================ function calcMint1t1USE(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } // Must be internal because of the struct function calcMintFractionalUSE(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { (uint256 mint_amount1, uint256 collateral_need_d18_1, uint256 shares_needed1) = calcMintFractionalWithCollateral(params); (uint256 mint_amount2, uint256 collateral_need_d18_2, uint256 shares_needed2) = calcMintFractionalWithShare(params); if(mint_amount1 > mint_amount2){ return (mint_amount2,collateral_need_d18_2,shares_needed2); }else{ return (mint_amount1,collateral_need_d18_1,shares_needed1); } } // Must be internal because of the struct function calcMintFractionalWithCollateral(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint USE. We do this by seeing the minimum mintable USE based on each amount uint256 c_dollar_value_d18_with_precision = params.collateral_amount.mul(params.col_price_usd); uint256 c_dollar_value_d18 = c_dollar_value_d18_with_precision.div(1e6); uint calculated_shares_dollar_value_d18 = (c_dollar_value_d18_with_precision.div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_shares_needed = calculated_shares_dollar_value_d18.mul(1e6).div(params.shares_price_usd); return ( c_dollar_value_d18.add(calculated_shares_dollar_value_d18), params.collateral_amount, calculated_shares_needed ); } // Must be internal because of the struct function calcMintFractionalWithShare(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint USE. We do this by seeing the minimum mintable USE based on each amount uint256 shares_dollar_value_d18_with_precision = params.shares_amount.mul(params.shares_price_usd); uint256 shares_dollar_value_d18 = shares_dollar_value_d18_with_precision.div(1e6); uint calculated_collateral_dollar_value_d18 = shares_dollar_value_d18_with_precision.mul(params.col_ratio) .div(COLLATERAL_RATIO_PRECISION.sub(params.col_ratio)).div(1e6); uint calculated_collateral_needed = calculated_collateral_dollar_value_d18.mul(1e6).div(params.col_price_usd); return ( shares_dollar_value_d18.add(calculated_collateral_dollar_value_d18), calculated_collateral_needed, params.shares_amount ); } function calcRedeem1t1USE(uint256 col_price_usd, uint256 use_amount) public pure returns (uint256) { return use_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackShares(BuybackShares_Params memory params) public pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible Shares with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 shares_dollar_value_d18 = params.shares_amount.mul(params.shares_price_usd).div(1e6); require(shares_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of Shares provided uint256 collateral_equivalent_d18 = shares_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeUSEInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // File: contracts\USE\Pools\USEPool.sol // License: MIT abstract contract USEPool is USEPoolAlgo,ContractGuard,AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ IERC20Detail public collateral_token; address public collateral_address; address public owner_address; address public community_address; address public use_contract_address; address public shares_contract_address; address public timelock_address; IShareToken private SHARE; IUSEStablecoin private USE; uint256 public minting_tax_base; uint256 public minting_tax_multiplier; uint256 public minting_required_reserve_ratio; uint256 public redemption_gcr_adj = PRECISION; // PRECISION/PRECISION = 1 uint256 public redemption_tax_base; uint256 public redemption_tax_multiplier; uint256 public redemption_tax_exponent; uint256 public redemption_required_reserve_ratio = 800000; uint256 public buyback_tax; uint256 public recollat_tax; uint256 public community_rate_ratio = 15000; uint256 public community_rate_in_use; uint256 public community_rate_in_share; mapping (address => uint256) public redeemSharesBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolShares; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 public constant PRECISION = 1e6; uint256 public constant RESERVE_RATIO_PRECISION = 1e6; uint256 public constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 public immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 10000000000e18; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on Shares minted during recollateralizeUSE(); 6 decimals of precision, set to 0.5% on genesis uint256 public bonus_rate = 5000; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 2; uint256 public global_use_supply_adj = 1000e18; //genesis_supply // AccessControl Roles bytes32 public constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 public constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 public constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 public constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 public constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); bytes32 public constant COMMUNITY_RATER = keccak256("COMMUNITY_RATER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; event UpdateOracleBonus(address indexed user,bool bonus1, bool bonus2); /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); require(redemptionOpened() == true,"Redeeming is closed"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); require(mintingOpened() == true,"Minting is closed"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _use_contract_address, address _shares_contract_address, address _collateral_address, address _creator_address, address _timelock_address, address _community_address ) public { USE = IUSEStablecoin(_use_contract_address); SHARE = IShareToken(_shares_contract_address); use_contract_address = _use_contract_address; shares_contract_address = _shares_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = _creator_address; community_address = _community_address; collateral_token = IERC20Detail(_collateral_address); missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); grantRole(COMMUNITY_RATER, _community_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this USE pool function collatDollarBalance() public view returns (uint256) { uint256 collateral_amount = collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral); uint256 collat_usd_price = collateralPricePaused == true ? pausedPrice : getCollateralPrice(); return collateral_amount.mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); } // Returns the value of excess collateral held in this USE pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = USE.totalSupply().sub(global_use_supply_adj); uint256 global_collat_value = USE.globalCollateralValue(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); // Handles an overcollateralized contract with CR > 1 if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) { global_collateral_ratio = COLLATERAL_RATIO_PRECISION; } // Calculates collateral needed to back each 1 USE with $1 of collateral at current collat ratio uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); if (global_collat_value > required_collat_dollar_value_d18) { return global_collat_value.sub(required_collat_dollar_value_d18); } return 0; } /* ========== PUBLIC FUNCTIONS ========== */ function getCollateralPrice() public view virtual returns (uint256); function getCollateralAmount() public view returns (uint256){ return collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral); } function requiredReserveRatio() public view returns(uint256){ uint256 pool_collateral_amount = getCollateralAmount(); uint256 swap_collateral_amount = USE.swapCollateralAmount(); require(swap_collateral_amount>0,"swap collateral is empty?"); return pool_collateral_amount.mul(RESERVE_RATIO_PRECISION).div(swap_collateral_amount); } function mintingOpened() public view returns(bool){ return (requiredReserveRatio() >= minting_required_reserve_ratio); } function redemptionOpened() public view returns(bool){ return (requiredReserveRatio() >= redemption_required_reserve_ratio); } // function mintingTax() public view returns(uint256){ uint256 _dynamicTax = minting_tax_multiplier.mul(requiredReserveRatio()).div(RESERVE_RATIO_PRECISION); return minting_tax_base + _dynamicTax; } function dynamicRedemptionTax(uint256 ratio,uint256 multiplier,uint256 exponent) public pure returns(uint256){ return multiplier.mul(RESERVE_RATIO_PRECISION**exponent).div(ratio**exponent); } // function redemptionTax() public view returns(uint256){ uint256 _dynamicTax =dynamicRedemptionTax(requiredReserveRatio(),redemption_tax_multiplier,redemption_tax_exponent); return redemption_tax_base + _dynamicTax; } function updateOraclePrice() public { IUniswapPairOracle _useDaiOracle = USE.USEDAIOracle(); IUniswapPairOracle _useSharesOracle = USE.USESharesOracle(); bool _bonus1 = _useDaiOracle.update(); bool _bonus2 = _useSharesOracle.update(); if(_bonus1 || _bonus2){ emit UpdateOracleBonus(msg.sender,_bonus1,_bonus2); } } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1USE(uint256 collateral_amount, uint256 use_out_min) external onlyOneBlock notMintPaused { updateOraclePrice(); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(USE.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require(getCollateralAmount().add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 use_amount_d18) = calcMint1t1USE( getCollateralPrice(), collateral_amount_d18 ); //1 USE for each $1 worth of collateral community_rate_in_use = community_rate_in_use.add(use_amount_d18.mul(community_rate_ratio).div(PRECISION)); use_amount_d18 = (use_amount_d18.mul(uint(1e6).sub(mintingTax()))).div(1e6); //remove precision at the end require(use_out_min <= use_amount_d18, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); USE.pool_mint(msg.sender, use_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalUSE(uint256 collateral_amount, uint256 shares_amount, uint256 use_out_min) external onlyOneBlock notMintPaused { updateOraclePrice(); uint256 share_price = USE.share_price(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(getCollateralAmount().add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more USE can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); MintFU_Params memory input_params = MintFU_Params( share_price, getCollateralPrice(), shares_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount,uint256 collateral_need_d18, uint256 shares_needed) = calcMintFractionalUSE(input_params); community_rate_in_use = community_rate_in_use.add(mint_amount.mul(community_rate_ratio).div(PRECISION)); mint_amount = (mint_amount.mul(uint(1e6).sub(mintingTax()))).div(1e6); require(use_out_min <= mint_amount, "Slippage limit reached"); require(shares_needed <= shares_amount, "Not enough Shares inputted"); uint256 collateral_need = collateral_need_d18.div(10 ** missing_decimals); SHARE.pool_burn_from(msg.sender, shares_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_need); USE.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1USE(uint256 use_amount, uint256 COLLATERAL_out_min) external onlyOneBlock notRedeemPaused { updateOraclePrice(); require(USE.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 use_amount_precision = use_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = calcRedeem1t1USE( getCollateralPrice(), use_amount_precision ); community_rate_in_use = community_rate_in_use.add(use_amount.mul(community_rate_ratio).div(PRECISION)); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemptionTax()))).div(1e6); require(collateral_needed <= getCollateralAmount(), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end USE.pool_burn_from(msg.sender, use_amount); require(redemptionOpened() == true,"Redeem amount too large !"); } // Will fail if fully collateralized or algorithmic // Redeem USE for collateral and SHARE. > 0% and < 100% collateral-backed function redeemFractionalUSE(uint256 use_amount, uint256 shares_out_min, uint256 COLLATERAL_out_min) external onlyOneBlock notRedeemPaused { updateOraclePrice(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); global_collateral_ratio = global_collateral_ratio.mul(redemption_gcr_adj).div(PRECISION); uint256 use_amount_post_tax = (use_amount.mul(uint(1e6).sub(redemptionTax()))).div(PRICE_PRECISION); uint256 shares_dollar_value_d18 = use_amount_post_tax.sub(use_amount_post_tax.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 shares_amount = shares_dollar_value_d18.mul(PRICE_PRECISION).div(USE.share_price()); // Need to adjust for decimals of collateral uint256 use_amount_precision = use_amount_post_tax.div(10 ** missing_decimals); uint256 collateral_dollar_value = use_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(getCollateralPrice()); require(collateral_amount <= getCollateralAmount(), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(shares_out_min <= shares_amount, "Slippage limit reached [Shares]"); community_rate_in_use = community_rate_in_use.add(use_amount.mul(community_rate_ratio).div(PRECISION)); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemSharesBalances[msg.sender] = redeemSharesBalances[msg.sender].add(shares_amount); unclaimedPoolShares = unclaimedPoolShares.add(shares_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end USE.pool_burn_from(msg.sender, use_amount); SHARE.pool_mint(address(this), shares_amount); require(redemptionOpened() == true,"Redeem amount too large !"); } // After a redemption happens, transfer the newly minted Shares and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out USE/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external onlyOneBlock{ require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendShares = false; bool sendCollateral = false; uint sharesAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemSharesBalances[msg.sender] > 0){ sharesAmount = redeemSharesBalances[msg.sender]; redeemSharesBalances[msg.sender] = 0; unclaimedPoolShares = unclaimedPoolShares.sub(sharesAmount); sendShares = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendShares == true){ SHARE.transfer(msg.sender, sharesAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of Shares to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get Shares for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of Shares + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra Shares value from the bonus rate as an arb opportunity function recollateralizeUSE(uint256 collateral_amount, uint256 shares_out_min) external onlyOneBlock { require(recollateralizePaused == false, "Recollateralize is paused"); updateOraclePrice(); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 share_price = USE.share_price(); uint256 use_total_supply = USE.totalSupply().sub(global_use_supply_adj); uint256 global_collateral_ratio = USE.global_collateral_ratio(); uint256 global_collat_value = USE.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = calcRecollateralizeUSEInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, use_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 shares_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_tax)).div(share_price); require(shares_out_min <= shares_paid_back, "Slippage limit reached"); community_rate_in_share = community_rate_in_share.add(shares_paid_back.mul(community_rate_ratio).div(PRECISION)); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); SHARE.pool_mint(msg.sender, shares_paid_back); } // Function can be called by an Shares holder to have the protocol buy back Shares with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackShares(uint256 shares_amount, uint256 COLLATERAL_out_min) external onlyOneBlock { require(buyBackPaused == false, "Buyback is paused"); updateOraclePrice(); uint256 share_price = USE.share_price(); BuybackShares_Params memory input_params = BuybackShares_Params( availableExcessCollatDV(), share_price, getCollateralPrice(), shares_amount ); (uint256 collateral_equivalent_d18) = (calcBuyBackShares(input_params)).mul(uint(1e6).sub(buyback_tax)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); community_rate_in_share = community_rate_in_share.add(shares_amount.mul(community_rate_ratio).div(PRECISION)); // Give the sender their desired collateral and burn the Shares SHARE.pool_burn_from(msg.sender, shares_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } function toggleCommunityInSharesRate(uint256 _rate) external{ require(community_rate_in_share>0,"No SHARE rate"); require(hasRole(COMMUNITY_RATER, msg.sender)); uint256 _amount_rate = community_rate_in_share.mul(_rate).div(PRECISION); community_rate_in_share = community_rate_in_share.sub(_amount_rate); SHARE.pool_mint(msg.sender,_amount_rate); } function toggleCommunityInUSERate(uint256 _rate) external{ require(community_rate_in_use>0,"No USE rate"); require(hasRole(COMMUNITY_RATER, msg.sender)); uint256 _amount_rate_use = community_rate_in_use.mul(_rate).div(PRECISION); community_rate_in_use = community_rate_in_use.sub(_amount_rate_use); uint256 _share_price_use = USE.share_price_in_use(); uint256 _amount_rate = _amount_rate_use.mul(PRICE_PRECISION).div(_share_price_use); SHARE.pool_mint(msg.sender,_amount_rate); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_buyback_tax, uint256 new_recollat_tax, uint256 use_supply_adj) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; buyback_tax = new_buyback_tax; recollat_tax = new_recollat_tax; global_use_supply_adj = use_supply_adj; } function setMintingParameters(uint256 _ratioLevel, uint256 _tax_base, uint256 _tax_multiplier) external onlyByOwnerOrGovernance{ minting_required_reserve_ratio = _ratioLevel; minting_tax_base = _tax_base; minting_tax_multiplier = _tax_multiplier; } function setRedemptionParameters(uint256 _ratioLevel, uint256 _tax_base, uint256 _tax_multiplier, uint256 _tax_exponent, uint256 _redeem_gcr_adj) external onlyByOwnerOrGovernance{ redemption_required_reserve_ratio = _ratioLevel; redemption_tax_base = _tax_base; redemption_tax_multiplier = _tax_multiplier; redemption_tax_exponent = _tax_exponent; redemption_gcr_adj = _redeem_gcr_adj; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setCommunityParameters(address _community_address,uint256 _ratio) external onlyByOwnerOrGovernance { community_address = _community_address; community_rate_ratio = _ratio; } /* ========== EVENTS ========== */ } // File: contracts\USE\Pools\USEPoolDAI.sol // License: MIT contract USEPoolDAI is USEPool { address public DAI_address; constructor( address _use_contract_address, address _shares_contract_address, address _collateral_address, address _creator_address, address _timelock_address, address _community_address ) USEPool(_use_contract_address, _shares_contract_address, _collateral_address, _creator_address, _timelock_address,_community_address) public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DAI_address = _collateral_address; } // Returns the price of the pool collateral in USD function getCollateralPrice() public view override returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { //Only For Dai return 1 * PRICE_PRECISION; } } }
Will fail if fully collateralized or fully algorithmic > 0% and < 100% collateral-backed
function mintFractionalUSE(uint256 collateral_amount, uint256 shares_amount, uint256 use_out_min) external onlyOneBlock notMintPaused { updateOraclePrice(); uint256 share_price = USE.share_price(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(getCollateralAmount().add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more USE can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); MintFU_Params memory input_params = MintFU_Params( share_price, getCollateralPrice(), shares_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount,uint256 collateral_need_d18, uint256 shares_needed) = calcMintFractionalUSE(input_params); community_rate_in_use = community_rate_in_use.add(mint_amount.mul(community_rate_ratio).div(PRECISION)); mint_amount = (mint_amount.mul(uint(1e6).sub(mintingTax()))).div(1e6); require(use_out_min <= mint_amount, "Slippage limit reached"); require(shares_needed <= shares_amount, "Not enough Shares inputted"); uint256 collateral_need = collateral_need_d18.div(10 ** missing_decimals); SHARE.pool_burn_from(msg.sender, shares_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_need); USE.pool_mint(msg.sender, mint_amount); }
10,485,692
[ 1, 13670, 2321, 309, 7418, 4508, 2045, 287, 1235, 578, 7418, 4886, 335, 405, 374, 9, 471, 411, 2130, 9, 4508, 2045, 287, 17, 823, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 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, 312, 474, 13724, 287, 8001, 12, 11890, 5034, 4508, 2045, 287, 67, 8949, 16, 2254, 5034, 24123, 67, 8949, 16, 2254, 5034, 999, 67, 659, 67, 1154, 13, 3903, 1338, 3335, 1768, 486, 49, 474, 28590, 288, 203, 3639, 1089, 23601, 5147, 5621, 203, 3639, 2254, 5034, 7433, 67, 8694, 273, 14988, 18, 14419, 67, 8694, 5621, 203, 3639, 2254, 5034, 2552, 67, 12910, 2045, 287, 67, 9847, 273, 14988, 18, 6347, 67, 12910, 2045, 287, 67, 9847, 5621, 203, 3639, 2583, 12, 6347, 67, 12910, 2045, 287, 67, 9847, 411, 5597, 12190, 654, 1013, 67, 54, 789, 4294, 67, 6694, 597, 2552, 67, 12910, 2045, 287, 67, 9847, 405, 374, 16, 315, 13535, 2045, 287, 7169, 4260, 358, 506, 3086, 263, 2787, 1611, 471, 263, 22866, 8863, 203, 3639, 2583, 12, 588, 13535, 2045, 287, 6275, 7675, 1289, 12, 12910, 2045, 287, 67, 8949, 13, 1648, 2845, 67, 311, 4973, 16, 315, 2864, 5898, 4973, 8675, 16, 1158, 1898, 14988, 848, 506, 312, 474, 329, 598, 333, 4508, 2045, 287, 8863, 203, 3639, 2254, 5034, 4508, 2045, 287, 67, 8949, 67, 72, 2643, 273, 4508, 2045, 287, 67, 8949, 380, 261, 2163, 2826, 3315, 67, 31734, 1769, 203, 3639, 490, 474, 42, 57, 67, 1370, 3778, 810, 67, 2010, 273, 490, 474, 42, 57, 67, 1370, 12, 203, 5411, 7433, 67, 8694, 16, 203, 5411, 336, 13535, 2045, 287, 5147, 9334, 203, 5411, 24123, 67, 8949, 16, 203, 5411, 4508, 2045, 287, 67, 8949, 67, 72, 2643, 16, 203, 5411, 2552, 2 ]
pragma solidity 0.4.24; /* script to setup contracts after full redeploy on Rinkeby. called via StabilityBoardProxy (MultiSig) but deployer account is the only signer yet because these working on the new contracts only. Stability Board and pretoken signers will be added and deployer will be removed when setup is successful. */ contract Main0001_initFirstDeploy { address constant DEPLOYER_ACCOUNT = 0x7b534c2D0F9Ee973e0b6FE8D4000cA711A20f22e; address constant RATES_FEEDER_ACCOUNT = 0x8C58187a978979947b88824DCdA5Cb5fD4410387; // new contracts address constant preTokenProxyAddress = 0x1411b3B189B01f6e6d1eA883bFFcbD3a5224934C; address constant stabilityBoardProxyAddress = 0x4686f017D456331ed2C1de66e134D8d05B24413D; PreToken constant preToken = PreToken(0xeCb782B19Be6E657ae2D88831dD98145A00D32D5); Rates constant rates = Rates(0x4babbe57453e2b6AF125B4e304256fCBDf744480); FeeAccount constant feeAccount = FeeAccount(0xF6B541E1B5e001DCc11827C1A16232759aeA730a); AugmintReserves constant augmintReserves = AugmintReserves(0x633cb544b2EF1bd9269B2111fD2B66fC05cd3477); InterestEarnedAccount constant interestEarnedAccount = InterestEarnedAccount(0x5C1a44E07541203474D92BDD03f803ea74f6947c); TokenAEur constant tokenAEur = TokenAEur(0x86A635EccEFFfA70Ff8A6DB29DA9C8DB288E40D0); MonetarySupervisor constant monetarySupervisor = MonetarySupervisor(0x1Ca4F9d261707aF8A856020a4909B777da218868); LoanManager constant loanManager = LoanManager(0xCBeFaF199b800DEeB9EAd61f358EE46E06c54070); Locker constant locker = Locker(0x095c0F071Fd75875a6b5a1dEf3f3a993F591080c); Exchange constant exchange = Exchange(0x8b52b019d237d0bbe8Baedf219132D5254e0690b); function execute(Main0001_initFirstDeploy /* self, not used */) external { // called via StabilityBoardProxy require(address(this) == stabilityBoardProxyAddress, "only deploy via stabilityboardsigner"); /****************************************************************************** * Set up permissions ******************************************************************************/ // preToken Permissions bytes32[] memory preTokenPermissions = new bytes32[](2); // dynamic array needed for grantMultiplePermissions() preTokenPermissions[0] = "PreTokenSigner"; preTokenPermissions[1] = "PermissionGranter"; preToken.grantMultiplePermissions(preTokenProxyAddress, preTokenPermissions); // StabilityBoard rates.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); feeAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); interestEarnedAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); tokenAEur.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); augmintReserves.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); monetarySupervisor.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); loanManager.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); locker.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); exchange.grantPermission(stabilityBoardProxyAddress, "StabilityBoard"); // RatesFeeder permissions to allow calling setRate() rates.grantPermission(RATES_FEEDER_ACCOUNT, "RatesFeeder"); // set NoTransferFee permissions feeAccount.grantPermission(feeAccount, "NoTransferFee"); feeAccount.grantPermission(augmintReserves, "NoTransferFee"); feeAccount.grantPermission(interestEarnedAccount, "NoTransferFee"); feeAccount.grantPermission(monetarySupervisor, "NoTransferFee"); feeAccount.grantPermission(loanManager, "NoTransferFee"); feeAccount.grantPermission(locker, "NoTransferFee"); feeAccount.grantPermission(exchange, "NoTransferFee"); // set MonetarySupervisor permissions interestEarnedAccount.grantPermission(monetarySupervisor, "MonetarySupervisor"); tokenAEur.grantPermission(monetarySupervisor, "MonetarySupervisor"); augmintReserves.grantPermission(monetarySupervisor, "MonetarySupervisor"); // set LoanManager permissions monetarySupervisor.grantPermission(loanManager, "LoanManager"); // set Locker permissions monetarySupervisor.grantPermission(locker, "Locker"); /****************************************************************************** * Add loan products ******************************************************************************/ // term (in sec), discountRate, loanCoverageRatio, minDisbursedAmount (w/ 4 decimals), defaultingFeePt, isActive loanManager.addLoanProduct(30 days, 990641, 600000, 1000, 50000, true); // 12% p.a. loanManager.addLoanProduct(14 days, 996337, 600000, 1000, 50000, true); // 10% p.a. loanManager.addLoanProduct(7 days, 998170, 600000, 1000, 50000, true); // 10% p.a. /****************************************************************************** * Add lock products ******************************************************************************/ // (perTermInterest, durationInSecs, minimumLockAmount, isActive) locker.addLockProduct(4019, 30 days, 1000, true); // 5% p.a. locker.addLockProduct(1506, 14 days, 1000, true); // 4% p.a. locker.addLockProduct(568, 7 days, 1000, true); // 3% p.a. /****************************************************************************** * Revoke PermissionGranter from deployer account * NB: migration scripts mistekanly granted it to deployer account (account[0]) * instead of StabilityBoardProxy in constructors ******************************************************************************/ preToken.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); rates.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); feeAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); augmintReserves.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); interestEarnedAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); tokenAEur.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); monetarySupervisor.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); loanManager.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); locker.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); exchange.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter"); /****************************************************************************** * Revoke PermissionGranter from this contract on preToken * NB: deploy script temporarly granted PermissionGranter to this script * now we can remove it as we granted it to preTokenProxy above ******************************************************************************/ preToken.revokePermission(stabilityBoardProxyAddress, "PermissionGranter"); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error TODO: check against ds-math: https://blog.dapphub.com/ds-math/ TODO: move roundedDiv to a sep lib? (eg. Math.sol) */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "mul overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "sub underflow"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function roundedDiv(uint a, uint b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 z = a / b; if (a % b >= b / 2) { z++; // no need for safe add b/c it can happen only if we divided the input } return z; } } /* Generic contract to authorise calls to certain functions only from a given address. The address authorised must be a contract (multisig or not, depending on the permission), except for local test deployment works as: 1. contract deployer account deploys contracts 2. constructor grants "PermissionGranter" permission to deployer account 3. deployer account executes initial setup (no multiSig) 4. deployer account grants PermissionGranter permission for the MultiSig contract (e.g. StabilityBoardProxy or PreTokenProxy) 5. deployer account revokes its own PermissionGranter permission */ contract Restricted { // NB: using bytes32 rather than the string type because it&#39;s cheaper gas-wise: mapping (address => mapping (bytes32 => bool)) public permissions; event PermissionGranted(address indexed agent, bytes32 grantedPermission); event PermissionRevoked(address indexed agent, bytes32 revokedPermission); modifier restrict(bytes32 requiredPermission) { require(permissions[msg.sender][requiredPermission], "msg.sender must have permission"); _; } constructor(address permissionGranterContract) public { require(permissionGranterContract != address(0), "permissionGranterContract must be set"); permissions[permissionGranterContract]["PermissionGranter"] = true; emit PermissionGranted(permissionGranterContract, "PermissionGranter"); } function grantPermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = true; emit PermissionGranted(agent, requiredPermission); } function grantMultiplePermissions(address agent, bytes32[] requiredPermissions) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { grantPermission(agent, requiredPermissions[i]); } } function revokePermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = false; emit PermissionRevoked(agent, requiredPermission); } function revokeMultiplePermissions(address agent, bytes32[] requiredPermissions) public { uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { revokePermission(agent, requiredPermissions[i]); } } } /* Abstract multisig contract to allow multi approval execution of atomic contracts scripts e.g. migrations or settings. * Script added by signing a script address by a signer (NEW state) * Script goes to ALLOWED state once a quorom of signers sign it (quorom fx is defined in each derived contracts) * Script can be signed even in APPROVED state * APPROVED scripts can be executed only once. - if script succeeds then state set to DONE - If script runs out of gas or reverts then script state set to FAILEd and not allowed to run again (To avoid leaving "behind" scripts which fail in a given state but eventually execute in the future) * Scripts can be cancelled by an other multisig script approved and calling cancelScript() * Adding/removing signers is only via multisig approved scripts using addSigners / removeSigners fxs */ contract MultiSig { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; mapping(address => bool) public isSigner; address[] public allSigners; // all signers, even the disabled ones // NB: it can contain duplicates when a signer is added, removed then readded again // the purpose of this array is to being able to iterate on signers in isSigner uint public activeSignersCount; enum ScriptState {New, Approved, Done, Cancelled, Failed} struct Script { ScriptState state; uint signCount; mapping(address => bool) signedBy; address[] allSigners; } mapping(address => Script) public scripts; address[] public scriptAddresses; event SignerAdded(address signer); event SignerRemoved(address signer); event ScriptSigned(address scriptAddress, address signer); event ScriptApproved(address scriptAddress); event ScriptCancelled(address scriptAddress); event ScriptExecuted(address scriptAddress, bool result); constructor() public { // deployer address is the first signer. Deployer can configure new contracts by itself being the only "signer" // The first script which sets the new contracts live should add signers and revoke deployer&#39;s signature right isSigner[msg.sender] = true; allSigners.push(msg.sender); activeSignersCount = 1; emit SignerAdded(msg.sender); } function sign(address scriptAddress) public { require(isSigner[msg.sender], "sender must be signer"); Script storage script = scripts[scriptAddress]; require(script.state == ScriptState.Approved || script.state == ScriptState.New, "script state must be New or Approved"); require(!script.signedBy[msg.sender], "script must not be signed by signer yet"); if(script.allSigners.length == 0) { // first sign of a new script scriptAddresses.push(scriptAddress); } script.allSigners.push(msg.sender); script.signedBy[msg.sender] = true; script.signCount = script.signCount.add(1); emit ScriptSigned(scriptAddress, msg.sender); if(checkQuorum(script.signCount)){ script.state = ScriptState.Approved; emit ScriptApproved(scriptAddress); } } function execute(address scriptAddress) public returns (bool result) { // only allow execute to signers to avoid someone set an approved script failed by calling it with low gaslimit require(isSigner[msg.sender], "sender must be signer"); Script storage script = scripts[scriptAddress]; require(script.state == ScriptState.Approved, "script state must be Approved"); /* init to failed because if delegatecall rans out of gas we won&#39;t have enough left to set it. NB: delegatecall leaves 63/64 part of gasLimit for the caller. Therefore the execute might revert with out of gas, leaving script in Approved state when execute() is called with small gas limits. */ script.state = ScriptState.Failed; // passing scriptAddress to allow called script access its own public fx-s if needed if(scriptAddress.delegatecall(bytes4(keccak256("execute(address)")), scriptAddress)) { script.state = ScriptState.Done; result = true; } else { result = false; } emit ScriptExecuted(scriptAddress, result); } function cancelScript(address scriptAddress) public { require(msg.sender == address(this), "only callable via MultiSig"); Script storage script = scripts[scriptAddress]; require(script.state == ScriptState.Approved || script.state == ScriptState.New, "script state must be New or Approved"); script.state= ScriptState.Cancelled; emit ScriptCancelled(scriptAddress); } /* requires quorum so it&#39;s callable only via a script executed by this contract */ function addSigners(address[] signers) public { require(msg.sender == address(this), "only callable via MultiSig"); for (uint i= 0; i < signers.length; i++) { if (!isSigner[signers[i]]) { require(signers[i] != address(0), "new signer must not be 0x0"); activeSignersCount++; allSigners.push(signers[i]); isSigner[signers[i]] = true; emit SignerAdded(signers[i]); } } } /* requires quorum so it&#39;s callable only via a script executed by this contract */ function removeSigners(address[] signers) public { require(msg.sender == address(this), "only callable via MultiSig"); for (uint i= 0; i < signers.length; i++) { if (isSigner[signers[i]]) { require(activeSignersCount > 1, "must not remove last signer"); activeSignersCount--; isSigner[signers[i]] = false; emit SignerRemoved(signers[i]); } } } /* implement it in derived contract */ function checkQuorum(uint signersCount) internal view returns(bool isQuorum); function getAllSignersCount() view external returns (uint allSignersCount) { return allSigners.length; } // UI helper fx - Returns signers from offset as [signer id (index in allSigners), address as uint, isActive 0 or 1] function getAllSigners(uint offset) external view returns(uint[3][CHUNK_SIZE] signersResult) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allSigners.length; i++) { address signerAddress = allSigners[i + offset]; signersResult[i] = [ i + offset, uint(signerAddress), isSigner[signerAddress] ? 1 : 0 ]; } } function getScriptsCount() view external returns (uint scriptsCount) { return scriptAddresses.length; } // UI helper fx - Returns scripts from offset as // [scriptId (index in scriptAddresses[]), address as uint, state, signCount] function getAllScripts(uint offset) external view returns(uint[4][CHUNK_SIZE] scriptsResult) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < scriptAddresses.length; i++) { address scriptAddress = scriptAddresses[i + offset]; scriptsResult[i] = [ i + offset, uint(scriptAddress), uint(scripts[scriptAddress].state), scripts[scriptAddress].signCount ]; } } } /* Augmint pretoken contract to record agreements and tokens allocated based on the agreement. Important: this is NOT an ERC20 token! PreTokens are non-fungible: agreements can have different conditions (valuationCap and discount) and pretokens are not tradable. Ownership can be transferred if owner wants to change wallet but the whole agreement and the total pretoken amount is moved to a new account PreTokenSigner can (via MultiSig): - add agreements and issue pretokens to an agreement - change owner of any agreement to handle if an owner lost a private keys - burn pretokens from any agreement to fix potential erroneous issuance These are known compromises on trustlessness hence all these tokens distributed based on signed agreements and preTokens are issued only to a closed group of contributors / team members. If despite these something goes wrong then as a last resort a new pretoken contract can be recreated from agreements. Some ERC20 functions are implemented so agreement owners can see their balances and use transfer in standard wallets. Restrictions: - only total balance can be transfered - effectively ERC20 transfer used to transfer agreement ownership - only agreement holders can transfer (i.e. can&#39;t transfer 0 amount if have no agreement to avoid polluting logs with Transfer events) - transfer is only allowed to accounts without an agreement yet - no approval and transferFrom ERC20 functions */ contract PreToken is Restricted { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; string constant public name = "Augmint pretokens"; // solhint-disable-line const-name-snakecase string constant public symbol = "APRE"; // solhint-disable-line const-name-snakecase uint8 constant public decimals = 0; // solhint-disable-line const-name-snakecase uint public totalSupply; struct Agreement { address owner; uint balance; uint32 discount; // discountRate in parts per million , ie. 10,000 = 1% uint32 valuationCap; // in USD (no decimals) } /* Agreement hash is the SHA-2 (SHA-256) hash of signed agreement document. To generate: OSX: shasum -a 256 agreement.pdf Windows: certUtil -hashfile agreement.pdf SHA256 */ mapping(address => bytes32) public agreementOwners; // to lookup agrement by owner mapping(bytes32 => Agreement) public agreements; bytes32[] public allAgreements; // all agreements to able to iterate over event Transfer(address indexed from, address indexed to, uint amount); event NewAgreement(address owner, bytes32 agreementHash, uint32 discount, uint32 valuationCap); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function addAgreement(address owner, bytes32 agreementHash, uint32 discount, uint32 valuationCap) external restrict("PreTokenSigner") { require(owner != address(0), "owner must not be 0x0"); require(agreementOwners[owner] == 0x0, "owner must not have an aggrement yet"); require(agreementHash != 0x0, "agreementHash must not be 0x0"); require(discount > 0, "discount must be > 0"); require(agreements[agreementHash].discount == 0, "agreement must not exist yet"); agreements[agreementHash] = Agreement(owner, 0, discount, valuationCap); agreementOwners[owner] = agreementHash; allAgreements.push(agreementHash); emit NewAgreement(owner, agreementHash, discount, valuationCap); } function issueTo(bytes32 agreementHash, uint amount) external restrict("PreTokenSigner") { Agreement storage agreement = agreements[agreementHash]; require(agreement.discount > 0, "agreement must exist"); agreement.balance = agreement.balance.add(amount); totalSupply = totalSupply.add(amount); emit Transfer(0x0, agreement.owner, amount); } /* Restricted function to allow pretoken signers to fix incorrect issuance */ function burnFrom(bytes32 agreementHash, uint amount) public restrict("PreTokenSigner") returns (bool) { Agreement storage agreement = agreements[agreementHash]; require(agreement.discount > 0, "agreement must exist"); // this is redundant b/c of next requires but be explicit require(amount > 0, "burn amount must be > 0"); require(agreement.balance >= amount, "must not burn more than balance"); // .sub would revert anyways but emit reason agreement.balance = agreement.balance.sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(agreement.owner, 0x0, amount); return true; } function balanceOf(address owner) public view returns (uint) { return agreements[agreementOwners[owner]].balance; } /* function to transfer agreement ownership to other wallet by owner it&#39;s in ERC20 form so owners can use standard ERC20 wallet just need to pass full balance as value */ function transfer(address to, uint amount) public returns (bool) { // solhint-disable-line no-simple-event-func-name require(amount == agreements[agreementOwners[msg.sender]].balance, "must transfer full balance"); _transfer(msg.sender, to); return true; } /* Restricted function to allow pretoken signers to fix if pretoken owner lost keys */ function transferAgreement(bytes32 agreementHash, address to) public restrict("PreTokenSigner") returns (bool) { _transfer(agreements[agreementHash].owner, to); return true; } /* private function used by transferAgreement & transfer */ function _transfer(address from, address to) private { Agreement storage agreement = agreements[agreementOwners[from]]; require(agreementOwners[from] != 0x0, "from agreement must exists"); require(agreementOwners[to] == 0, "to must not have an agreement"); require(to != 0x0, "must not transfer to 0x0"); agreement.owner = to; agreementOwners[to] = agreementOwners[from]; agreementOwners[from] = 0x0; emit Transfer(from, to, agreement.balance); } function getAgreementsCount() external view returns (uint agreementsCount) { return allAgreements.length; } // UI helper fx - Returns all agreements from offset as // [index in allAgreements, account address as uint, balance, agreementHash as uint, // discount as uint, valuationCap as uint ] function getAllAgreements(uint offset) external view returns(uint[6][CHUNK_SIZE] agreementsResult) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allAgreements.length; i++) { bytes32 agreementHash = allAgreements[i + offset]; Agreement storage agreement = agreements[agreementHash]; agreementsResult[i] = [ i + offset, uint(agreement.owner), agreement.balance, uint(agreementHash), uint(agreement.discount), uint(agreement.valuationCap)]; } } } /* Generic symbol / WEI rates contract. only callable by trusted price oracles. Being regularly called by a price oracle TODO: trustless/decentrilezed price Oracle TODO: shall we use blockNumber instead of now for lastUpdated? TODO: consider if we need storing rates with variable decimals instead of fixed 4 TODO: could we emit 1 RateChanged event from setMultipleRates (symbols and newrates arrays)? */ contract Rates is Restricted { using SafeMath for uint256; struct RateInfo { uint rate; // how much 1 WEI worth 1 unit , i.e. symbol/ETH rate // 0 rate means no rate info available uint lastUpdated; } // mapping currency symbol => rate. all rates are stored with 4 decimals. i.e. ETH/EUR = 989.12 then rate = 989,1200 mapping(bytes32 => RateInfo) public rates; event RateChanged(bytes32 symbol, uint newRate); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function setRate(bytes32 symbol, uint newRate) external restrict("RatesFeeder") { rates[symbol] = RateInfo(newRate, now); emit RateChanged(symbol, newRate); } function setMultipleRates(bytes32[] symbols, uint[] newRates) external restrict("RatesFeeder") { require(symbols.length == newRates.length, "symobls and newRates lengths must be equal"); for (uint256 i = 0; i < symbols.length; i++) { rates[symbols[i]] = RateInfo(newRates[i], now); emit RateChanged(symbols[i], newRates[i]); } } function convertFromWei(bytes32 bSymbol, uint weiValue) external view returns(uint value) { require(rates[bSymbol].rate > 0, "rates[bSymbol] must be > 0"); return weiValue.mul(rates[bSymbol].rate).roundedDiv(1000000000000000000); } function convertToWei(bytes32 bSymbol, uint value) external view returns(uint weiValue) { // next line would revert with div by zero but require to emit reason require(rates[bSymbol].rate > 0, "rates[bSymbol] must be > 0"); /* TODO: can we make this not loosing max scale? */ return value.mul(1000000000000000000).roundedDiv(rates[bSymbol].rate); } } contract SystemAccount is Restricted { event WithdrawFromSystemAccount(address tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks /* TODO: this is only for first pilots to avoid funds stuck in contract due to bugs. remove this function for higher volume pilots */ function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative) external restrict("StabilityBoard") { tokenAddress.transferWithNarrative(to, tokenAmount, narrative); if (weiAmount > 0) { to.transfer(weiAmount); } emit WithdrawFromSystemAccount(tokenAddress, to, tokenAmount, weiAmount, narrative); } } interface TokenReceiver { function transferNotification(address from, uint256 amount, uint data) external; } interface TransferFeeInterface { function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee); } interface ExchangeFeeInterface { function calculateExchangeFee(uint weiAmount) external view returns (uint256 weiFee); } interface ERC20Interface { event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed from, address indexed to, uint amount); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function balanceOf(address who) external view returns (uint); function allowance(address _owner, address _spender) external view returns (uint remaining); } /* Augmint Token interface (abstract contract) TODO: overload transfer() & transferFrom() instead of transferWithNarrative() & transferFromWithNarrative() when this fix available in web3& truffle also uses that web3: https://github.com/ethereum/web3.js/pull/1185 TODO: shall we use bytes for narrative? */ contract AugmintTokenInterface is Restricted, ERC20Interface { using SafeMath for uint256; string public name; string public symbol; bytes32 public peggedSymbol; uint8 public decimals; uint public totalSupply; mapping(address => uint256) public balances; // Balances for each account mapping(address => mapping (address => uint256)) public allowed; // allowances added with approve() address public stabilityBoardProxy; TransferFeeInterface public feeAccount; mapping(bytes32 => bool) public delegatedTxHashesUsed; // record txHashes used by delegatedTransfer event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax); event Transfer(address indexed from, address indexed to, uint amount); event AugmintTransfer(address indexed from, address indexed to, uint amount, string narrative, uint fee); event TokenIssued(uint amount); event TokenBurned(uint amount); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function increaseApproval(address spender, uint addedValue) external returns (bool); function decreaseApproval(address spender, uint subtractedValue) external returns (bool); function issueTo(address to, uint amount) external; // restrict it to "MonetarySupervisor" in impl.; function burn(uint amount) external; function transferAndNotify(TokenReceiver target, uint amount, uint data) external; function transferWithNarrative(address to, uint256 amount, string narrative) external; function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external; function allowance(address owner, address spender) external view returns (uint256 remaining); function balanceOf(address who) external view returns (uint); } /** * @title Eliptic curve signature operations * * @dev Based on https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ECRecovery.sol * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } /* Generic Augmint Token implementation (ERC20 token) This contract manages: * Balances of Augmint holders and transactions between them * Issues/burns tokens TODO: - reconsider delegatedTransfer and how to structure it - shall we allow change of txDelegator? - consider generic bytes arg instead of uint for transferAndNotify - consider separate transfer fee params and calculation to separate contract (to feeAccount?) */ contract AugmintToken is AugmintTokenInterface { event FeeAccountChanged(TransferFeeInterface newFeeAccount); constructor(address permissionGranterContract, string _name, string _symbol, bytes32 _peggedSymbol, uint8 _decimals, TransferFeeInterface _feeAccount) public Restricted(permissionGranterContract) { require(_feeAccount != address(0), "feeAccount must be set"); require(bytes(_name).length > 0, "name must be set"); require(bytes(_symbol).length > 0, "symbol must be set"); name = _name; symbol = _symbol; peggedSymbol = _peggedSymbol; decimals = _decimals; feeAccount = _feeAccount; } function transfer(address to, uint256 amount) external returns (bool) { _transfer(msg.sender, to, amount, ""); return true; } /* Transfers based on an offline signed transfer instruction. */ function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, to, amount, narrative); } function approve(address _spender, uint256 amount) external returns (bool) { require(_spender != 0x0, "spender must be set"); allowed[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, amount); return true; } /** ERC20 transferFrom attack protection: https://github.com/DecentLabs/dcm-poc/issues/57 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) Based on MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) external returns (bool) { return _increaseApproval(msg.sender, _spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function transferFrom(address from, address to, uint256 amount) external returns (bool) { _transferFrom(from, to, amount, ""); return true; } // Issue tokens. See MonetarySupervisor but as a rule of thumb issueTo is only allowed: // - on new loan (by trusted Lender contracts) // - when converting old tokens using MonetarySupervisor // - strictly to reserve by Stability Board (via MonetarySupervisor) function issueTo(address to, uint amount) external restrict("MonetarySupervisor") { balances[to] = balances[to].add(amount); totalSupply = totalSupply.add(amount); emit Transfer(0x0, to, amount); emit AugmintTransfer(0x0, to, amount, "", 0); } // Burn tokens. Anyone can burn from its own account. YOLO. // Used by to burn from Augmint reserve or by Lender contract after loan repayment function burn(uint amount) external { require(balances[msg.sender] >= amount, "balance must be >= amount"); balances[msg.sender] = balances[msg.sender].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(msg.sender, 0x0, amount); emit AugmintTransfer(msg.sender, 0x0, amount, "", 0); } /* to upgrade feeAccount (eg. for fee calculation changes) */ function setFeeAccount(TransferFeeInterface newFeeAccount) external restrict("StabilityBoard") { feeAccount = newFeeAccount; emit FeeAccountChanged(newFeeAccount); } /* transferAndNotify can be used by contracts which require tokens to have only 1 tx (instead of approve + call) Eg. repay loan, lock funds, token sell order on exchange Reverts on failue: - transfer fails - if transferNotification fails (callee must revert on failure) - if targetContract is an account or targetContract doesn&#39;t have neither transferNotification or fallback fx TODO: make data param generic bytes (see receiver code attempt in Locker.transferNotification) */ function transferAndNotify(TokenReceiver target, uint amount, uint data) external { _transfer(msg.sender, target, amount, ""); target.transferNotification(msg.sender, amount, data); } /* transferAndNotify based on an instruction signed offline */ function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, target, amount, ""); target.transferNotification(from, amount, data); } function transferWithNarrative(address to, uint256 amount, string narrative) external { _transfer(msg.sender, to, amount, narrative); } function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external { _transferFrom(from, to, amount, narrative); } function balanceOf(address _owner) external view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } function _checkHashAndTransferExecutorFee(bytes32 txHash, bytes signature, address signer, uint maxExecutorFeeInToken, uint requestedExecutorFeeInToken) private { require(requestedExecutorFeeInToken <= maxExecutorFeeInToken, "requestedExecutorFee must be <= maxExecutorFee"); require(!delegatedTxHashesUsed[txHash], "txHash already used"); delegatedTxHashesUsed[txHash] = true; address recovered = ECRecovery.recover(ECRecovery.toEthSignedMessageHash(txHash), signature); require(recovered == signer, "invalid signature"); _transfer(signer, msg.sender, requestedExecutorFeeInToken, "Delegated transfer fee", 0); } function _increaseApproval(address _approver, address _spender, uint _addedValue) private returns (bool) { allowed[_approver][_spender] = allowed[_approver][_spender].add(_addedValue); emit Approval(_approver, _spender, allowed[_approver][_spender]); } function _transferFrom(address from, address to, uint256 amount, string narrative) private { require(balances[from] >= amount, "balance must >= amount"); require(allowed[from][msg.sender] >= amount, "allowance must be >= amount"); // don&#39;t allow 0 transferFrom if no approval: require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount"); /* NB: fee is deducted from owner. It can result that transferFrom of amount x to fail when x + fee is not availale on owner balance */ _transfer(from, to, amount, narrative); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); } function _transfer(address from, address to, uint transferAmount, string narrative) private { uint fee = feeAccount.calculateTransferFee(from, to, transferAmount); _transfer(from, to, transferAmount, narrative, fee); } function _transfer(address from, address to, uint transferAmount, string narrative, uint fee) private { require(to != 0x0, "to must be set"); uint amountWithFee = transferAmount.add(fee); // to emit proper reason instead of failing on from.sub() require(balances[from] >= amountWithFee, "balance must be >= amount + transfer fee"); if (fee > 0) { balances[feeAccount] = balances[feeAccount].add(fee); emit Transfer(from, feeAccount, fee); } balances[from] = balances[from].sub(amountWithFee); balances[to] = balances[to].add(transferAmount); emit Transfer(from, to, transferAmount); emit AugmintTransfer(from, to, transferAmount, narrative, fee); } } /* Contract to collect fees from system TODO: calculateExchangeFee + Exchange params and setters */ contract FeeAccount is SystemAccount, TransferFeeInterface { using SafeMath for uint256; struct TransferFee { uint pt; // in parts per million (ppm) , ie. 2,000 = 0.2% uint min; // with base unit of augmint token, eg. 2 decimals for token, eg. 310 = 3.1 ACE uint max; // with base unit of augmint token, eg. 2 decimals for token, eg. 310 = 3.1 ACE } TransferFee public transferFee; event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax); constructor(address permissionGranterContract, uint transferFeePt, uint transferFeeMin, uint transferFeeMax) public SystemAccount(permissionGranterContract) { transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax); } function () public payable { // solhint-disable-line no-empty-blocks // to accept ETH sent into feeAccount (defaulting fee in ETH ) } function setTransferFees(uint transferFeePt, uint transferFeeMin, uint transferFeeMax) external restrict("StabilityBoard") { transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax); emit TransferFeesChanged(transferFeePt, transferFeeMin, transferFeeMax); } function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee) { if (!permissions[from]["NoTransferFee"] && !permissions[to]["NoTransferFee"]) { fee = amount.mul(transferFee.pt).div(1000000); if (fee > transferFee.max) { fee = transferFee.max; } else if (fee < transferFee.min) { fee = transferFee.min; } } return fee; } function calculateExchangeFee(uint weiAmount) external view returns (uint256 weiFee) { /* TODO: to be implemented and use in Exchange.sol. always revert for now */ require(weiAmount != weiAmount, "not yet implemented"); weiFee = transferFee.max; // to silence compiler warnings until it&#39;s implemented } } /* Contract to hold earned interest from loans repaid premiums for locks are being accrued (i.e. transferred) to Locker */ contract InterestEarnedAccount is SystemAccount { constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function transferInterest(AugmintTokenInterface augmintToken, address locker, uint interestAmount) external restrict("MonetarySupervisor") { augmintToken.transfer(locker, interestAmount); } } /* Contract to hold Augmint reserves (ETH & Token) - ETH as regular ETH balance of the contract - ERC20 token reserve (stored as regular Token balance under the contract address) NB: reserves are held under the contract address, therefore any transaction on the reserve is limited to the tx-s defined here (i.e. transfer is not allowed even by the contract owner or StabilityBoard or MonetarySupervisor) */ contract AugmintReserves is SystemAccount { function () public payable { // solhint-disable-line no-empty-blocks // to accept ETH sent into reserve (from defaulted loan&#39;s collateral ) } constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function burn(AugmintTokenInterface augmintToken, uint amount) external restrict("MonetarySupervisor") { augmintToken.burn(amount); } } /* MonetarySupervisor - maintains system wide KPIs (eg totalLockAmount, totalLoanAmount) - holds system wide parameters/limits - enforces system wide limits - burns and issues to AugmintReserves - Send funds from reserve to exchange when intervening (not implemented yet) - Converts older versions of AugmintTokens in 1:1 to new */ contract MonetarySupervisor is Restricted, TokenReceiver { // solhint-disable-line no-empty-blocks using SafeMath for uint256; uint public constant PERCENT_100 = 1000000; AugmintTokenInterface public augmintToken; InterestEarnedAccount public interestEarnedAccount; AugmintReserves public augmintReserves; uint public issuedByStabilityBoard; // token issued by Stability Board uint public totalLoanAmount; // total amount of all loans without interest, in token uint public totalLockedAmount; // total amount of all locks without premium, in token /********** Parameters to ensure totalLoanAmount or totalLockedAmount difference is within limits and system also works when total loan or lock amounts are low. for test calculations: https://docs.google.com/spreadsheets/d/1MeWYPYZRIm1n9lzpvbq8kLfQg1hhvk5oJY6NrR401S0 **********/ struct LtdParams { uint lockDifferenceLimit; /* only allow a new lock if Loan To Deposit ratio would stay above (1 - lockDifferenceLimit) with new lock. Stored as parts per million */ uint loanDifferenceLimit; /* only allow a new loan if Loan To Deposit ratio would stay above (1 + loanDifferenceLimit) with new loan. Stored as parts per million */ /* allowedDifferenceAmount param is to ensure the system is not "freezing" when totalLoanAmount or totalLockAmount is low. It allows a new loan or lock (up to an amount to reach this difference) even if LTD will go below / above lockDifferenceLimit / loanDifferenceLimit with the new lock/loan */ uint allowedDifferenceAmount; } LtdParams public ltdParams; /* Previously deployed AugmintTokens which are accepted for conversion (see transferNotification() ) NB: it&#39;s not iterable so old version addresses needs to be added for UI manually after each deploy */ mapping(address => bool) public acceptedLegacyAugmintTokens; event LtdParamsChanged(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount); event AcceptedLegacyAugmintTokenChanged(address augmintTokenAddress, bool newAcceptedState); event LegacyTokenConverted(address oldTokenAddress, address account, uint amount); event KPIsAdjusted(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment); event SystemContractsChanged(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, AugmintReserves _augmintReserves, InterestEarnedAccount _interestEarnedAccount, uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; augmintReserves = _augmintReserves; interestEarnedAccount = _interestEarnedAccount; ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } function issueToReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.add(amount); augmintToken.issueTo(augmintReserves, amount); } function burnFromReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.sub(amount); augmintReserves.burn(augmintToken, amount); } /* Locker requesting interest when locking funds. Enforcing LTD to stay within range allowed by LTD params NB: it does not know about min loan amount, it&#39;s the loan contract&#39;s responsibility to enforce it */ function requestInterest(uint amountToLock, uint interestAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); require(amountToLock <= getMaxLockAmountAllowedByLtd(), "amountToLock must be <= maxLockAmountAllowedByLtd"); totalLockedAmount = totalLockedAmount.add(amountToLock); // next line would revert but require to emit reason: require(augmintToken.balanceOf(address(interestEarnedAccount)) >= interestAmount, "interestEarnedAccount balance must be >= interestAmount"); interestEarnedAccount.transferInterest(augmintToken, msg.sender, interestAmount); // transfer interest to Locker } // Locker notifying when releasing funds to update KPIs function releaseFundsNotification(uint lockedAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); totalLockedAmount = totalLockedAmount.sub(lockedAmount); } /* Issue loan if LTD stays within range allowed by LTD params NB: it does not know about min loan amount, it&#39;s the loan contract&#39;s responsibility to enforce it */ function issueLoan(address borrower, uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); require(loanAmount <= getMaxLoanAmountAllowedByLtd(), "loanAmount must be <= maxLoanAmountAllowedByLtd"); totalLoanAmount = totalLoanAmount.add(loanAmount); augmintToken.issueTo(borrower, loanAmount); } function loanRepaymentNotification(uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(loanAmount); } // NB: this is called by Lender contract with the sum of all loans collected in batch function loanCollectionNotification(uint totalLoanAmountCollected) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(totalLoanAmountCollected); } function setAcceptedLegacyAugmintToken(address legacyAugmintTokenAddress, bool newAcceptedState) external restrict("StabilityBoard") { acceptedLegacyAugmintTokens[legacyAugmintTokenAddress] = newAcceptedState; emit AcceptedLegacyAugmintTokenChanged(legacyAugmintTokenAddress, newAcceptedState); } function setLtdParams(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) external restrict("StabilityBoard") { ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); emit LtdParamsChanged(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } /* function to migrate old totalLoanAmount and totalLockedAmount from old monetarySupervisor contract when it&#39;s upgraded. Set new monetarySupervisor contract in all locker and loanManager contracts before executing this */ function adjustKPIs(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment) external restrict("StabilityBoard") { totalLoanAmount = totalLoanAmount.add(totalLoanAmountAdjustment); totalLockedAmount = totalLockedAmount.add(totalLockedAmountAdjustment); emit KPIsAdjusted(totalLoanAmountAdjustment, totalLockedAmountAdjustment); } /* to allow upgrades of InterestEarnedAccount and AugmintReserves contracts. */ function setSystemContracts(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves) external restrict("StabilityBoard") { interestEarnedAccount = newInterestEarnedAccount; augmintReserves = newAugmintReserves; emit SystemContractsChanged(newInterestEarnedAccount, newAugmintReserves); } /* User can request to convert their tokens from older AugmintToken versions in 1:1 transferNotification is called from AugmintToken&#39;s transferAndNotify Flow for converting old tokens: 1) user calls old token contract&#39;s transferAndNotify with the amount to convert, addressing the new MonetarySupervisor Contract 2) transferAndNotify transfers user&#39;s old tokens to the current MonetarySupervisor contract&#39;s address 3) transferAndNotify calls MonetarySupervisor.transferNotification 4) MonetarySupervisor checks if old AugmintToken is permitted 5) MonetarySupervisor issues new tokens to user&#39;s account in current AugmintToken 6) MonetarySupervisor burns old tokens from own balance */ function transferNotification(address from, uint amount, uint /* data, not used */ ) external { AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender); require(acceptedLegacyAugmintTokens[legacyToken], "msg.sender must be allowed in acceptedLegacyAugmintTokens"); legacyToken.burn(amount); augmintToken.issueTo(from, amount); emit LegacyTokenConverted(msg.sender, from, amount); } function getLoanToDepositRatio() external view returns (uint loanToDepositRatio) { loanToDepositRatio = totalLockedAmount == 0 ? 0 : totalLockedAmount.mul(PERCENT_100).div(totalLoanAmount); } /* Helper function for UI. Returns max lock amount based on minLockAmount, interestPt, using LTD params & interestEarnedAccount balance */ function getMaxLockAmount(uint minLockAmount, uint interestPt) external view returns (uint maxLock) { uint allowedByEarning = augmintToken.balanceOf(address(interestEarnedAccount)).mul(PERCENT_100).div(interestPt); uint allowedByLtd = getMaxLockAmountAllowedByLtd(); maxLock = allowedByEarning < allowedByLtd ? allowedByEarning : allowedByLtd; maxLock = maxLock < minLockAmount ? 0 : maxLock; } /* Helper function for UI. Returns max loan amount based on minLoanAmont using LTD params */ function getMaxLoanAmount(uint minLoanAmount) external view returns (uint maxLoan) { uint allowedByLtd = getMaxLoanAmountAllowedByLtd(); maxLoan = allowedByLtd < minLoanAmount ? 0 : allowedByLtd; } /* returns maximum lockable token amount allowed by LTD params. */ function getMaxLockAmountAllowedByLtd() public view returns(uint maxLockByLtd) { uint allowedByLtdDifferencePt = totalLoanAmount.mul(PERCENT_100).div(PERCENT_100 .sub(ltdParams.lockDifferenceLimit)); allowedByLtdDifferencePt = totalLockedAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLockedAmount); uint allowedByLtdDifferenceAmount = totalLockedAmount >= totalLoanAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLoanAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLockedAmount); maxLockByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } /* returns maximum borrowable token amount allowed by LTD params */ function getMaxLoanAmountAllowedByLtd() public view returns(uint maxLoanByLtd) { uint allowedByLtdDifferencePt = totalLockedAmount.mul(ltdParams.loanDifferenceLimit.add(PERCENT_100)) .div(PERCENT_100); allowedByLtdDifferencePt = totalLoanAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLoanAmount); uint allowedByLtdDifferenceAmount = totalLoanAmount >= totalLockedAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLockedAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLoanAmount); maxLoanByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } } /* Augmint&#39;s Internal Exchange For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/exchangeFlow.png TODO: - change to wihtdrawal pattern, see: https://github.com/Augmint/augmint-contracts/issues/17 - deduct fee - consider take funcs (frequent rate changes with takeBuyToken? send more and send back remainder?) - use Rates interface? */ pragma solidity 0.4.24; contract Exchange is Restricted { using SafeMath for uint256; AugmintTokenInterface public augmintToken; Rates public rates; uint public constant CHUNK_SIZE = 100; struct Order { uint64 index; address maker; // % of published current peggedSymbol/ETH rates published by Rates contract. Stored as parts per million // I.e. 1,000,000 = 100% (parity), 990,000 = 1% below parity uint32 price; // buy order: amount in wei // sell order: token amount uint amount; } uint64 public orderCount; mapping(uint64 => Order) public buyTokenOrders; mapping(uint64 => Order) public sellTokenOrders; uint64[] private activeBuyOrders; uint64[] private activeSellOrders; /* used to stop executing matchMultiple when running out of gas. actual is much less, just leaving enough matchMultipleOrders() to finish TODO: fine tune & test it*/ uint32 private constant ORDER_MATCH_WORST_GAS = 100000; event NewOrder(uint64 indexed orderId, address indexed maker, uint32 price, uint tokenAmount, uint weiAmount); event OrderFill(address indexed tokenBuyer, address indexed tokenSeller, uint64 buyTokenOrderId, uint64 sellTokenOrderId, uint publishedRate, uint32 price, uint fillRate, uint weiAmount, uint tokenAmount); event CancelledOrder(uint64 indexed orderId, address indexed maker, uint tokenAmount, uint weiAmount); event RatesContractChanged(Rates newRatesContract); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, Rates _rates) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; rates = _rates; } /* to allow upgrade of Rates contract */ function setRatesContract(Rates newRatesContract) external restrict("StabilityBoard") { rates = newRatesContract; emit RatesContractChanged(newRatesContract); } function placeBuyTokenOrder(uint32 price) external payable returns (uint64 orderId) { require(price > 0, "price must be > 0"); require(msg.value > 0, "msg.value must be > 0"); orderId = ++orderCount; buyTokenOrders[orderId] = Order(uint64(activeBuyOrders.length), msg.sender, price, msg.value); activeBuyOrders.push(orderId); emit NewOrder(orderId, msg.sender, price, 0, msg.value); } /* this function requires previous approval to transfer tokens */ function placeSellTokenOrder(uint32 price, uint tokenAmount) external returns (uint orderId) { augmintToken.transferFrom(msg.sender, this, tokenAmount); return _placeSellTokenOrder(msg.sender, price, tokenAmount); } /* place sell token order called from AugmintToken&#39;s transferAndNotify Flow: 1) user calls token contract&#39;s transferAndNotify price passed in data arg 2) transferAndNotify transfers tokens to the Exchange contract 3) transferAndNotify calls Exchange.transferNotification with lockProductId */ function transferNotification(address maker, uint tokenAmount, uint price) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); _placeSellTokenOrder(maker, uint32(price), tokenAmount); } function cancelBuyTokenOrder(uint64 buyTokenId) external { Order storage order = buyTokenOrders[buyTokenId]; require(order.maker == msg.sender, "msg.sender must be order.maker"); require(order.amount > 0, "buy order already removed"); uint amount = order.amount; order.amount = 0; _removeBuyOrder(order); msg.sender.transfer(amount); emit CancelledOrder(buyTokenId, msg.sender, 0, amount); } function cancelSellTokenOrder(uint64 sellTokenId) external { Order storage order = sellTokenOrders[sellTokenId]; require(order.maker == msg.sender, "msg.sender must be order.maker"); require(order.amount > 0, "sell order already removed"); uint amount = order.amount; order.amount = 0; _removeSellOrder(order); augmintToken.transferWithNarrative(msg.sender, amount, "Sell token order cancelled"); emit CancelledOrder(sellTokenId, msg.sender, amount, 0); } /* matches any two orders if the sell price >= buy price trade price is the price of the maker (the order placed earlier) reverts if any of the orders have been removed */ function matchOrders(uint64 buyTokenId, uint64 sellTokenId) external { require(_fillOrder(buyTokenId, sellTokenId), "fill order failed"); } /* matches as many orders as possible from the passed orders Runs as long as gas is available for the call. Reverts if any match is invalid (e.g sell price > buy price) Skips match if any of the matched orders is removed / already filled (i.e. amount = 0) */ function matchMultipleOrders(uint64[] buyTokenIds, uint64[] sellTokenIds) external returns(uint matchCount) { uint len = buyTokenIds.length; require(len == sellTokenIds.length, "buyTokenIds and sellTokenIds lengths must be equal"); for (uint i = 0; i < len && gasleft() > ORDER_MATCH_WORST_GAS; i++) { if(_fillOrder(buyTokenIds[i], sellTokenIds[i])) { matchCount++; } } } function getActiveOrderCounts() external view returns(uint buyTokenOrderCount, uint sellTokenOrderCount) { return(activeBuyOrders.length, activeSellOrders.length); } // returns CHUNK_SIZE orders starting from offset // orders are encoded as [id, maker, price, amount] function getActiveBuyOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeBuyOrders.length; i++) { uint64 orderId = activeBuyOrders[offset + i]; Order storage order = buyTokenOrders[orderId]; response[i] = [orderId, uint(order.maker), order.price, order.amount]; } } function getActiveSellOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeSellOrders.length; i++) { uint64 orderId = activeSellOrders[offset + i]; Order storage order = sellTokenOrders[orderId]; response[i] = [orderId, uint(order.maker), order.price, order.amount]; } } function _fillOrder(uint64 buyTokenId, uint64 sellTokenId) private returns(bool success) { Order storage buy = buyTokenOrders[buyTokenId]; Order storage sell = sellTokenOrders[sellTokenId]; if( buy.amount == 0 || sell.amount == 0 ) { return false; // one order is already filled and removed. // we let matchMultiple continue, indivudal match will revert } require(buy.price >= sell.price, "buy price must be >= sell price"); // pick maker&#39;s price (whoever placed order sooner considered as maker) uint32 price = buyTokenId > sellTokenId ? sell.price : buy.price; uint publishedRate; (publishedRate, ) = rates.rates(augmintToken.peggedSymbol()); uint fillRate = publishedRate.mul(price).roundedDiv(1000000); uint sellWei = sell.amount.mul(1 ether).roundedDiv(fillRate); uint tradedWei; uint tradedTokens; if (sellWei <= buy.amount) { tradedWei = sellWei; tradedTokens = sell.amount; } else { tradedWei = buy.amount; tradedTokens = buy.amount.mul(fillRate).roundedDiv(1 ether); } buy.amount = buy.amount.sub(tradedWei); if (buy.amount == 0) { _removeBuyOrder(buy); } sell.amount = sell.amount.sub(tradedTokens); if (sell.amount == 0) { _removeSellOrder(sell); } augmintToken.transferWithNarrative(buy.maker, tradedTokens, "Buy token order fill"); sell.maker.transfer(tradedWei); emit OrderFill(buy.maker, sell.maker, buyTokenId, sellTokenId, publishedRate, price, fillRate, tradedWei, tradedTokens); return true; } function _placeSellTokenOrder(address maker, uint32 price, uint tokenAmount) private returns (uint64 orderId) { require(price > 0, "price must be > 0"); require(tokenAmount > 0, "tokenAmount must be > 0"); orderId = ++orderCount; sellTokenOrders[orderId] = Order(uint64(activeSellOrders.length), maker, price, tokenAmount); activeSellOrders.push(orderId); emit NewOrder(orderId, maker, price, tokenAmount, 0); } function _removeBuyOrder(Order storage order) private { _removeOrder(activeBuyOrders, order.index); } function _removeSellOrder(Order storage order) private { _removeOrder(activeSellOrders, order.index); } function _removeOrder(uint64[] storage orders, uint64 index) private { if (index < orders.length - 1) { orders[index] = orders[orders.length - 1]; } orders.length--; } } /* Augmint Crypto Euro token (A-EUR) implementation */ contract TokenAEur is AugmintToken { constructor(address _permissionGranterContract, TransferFeeInterface _feeAccount) public AugmintToken(_permissionGranterContract, "Augmint Crypto Euro", "AEUR", "EUR", 2, _feeAccount) {} // solhint-disable-line no-empty-blocks } /* Contract to manage Augmint token loan contracts backed by ETH For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/loanFlow.png TODO: - create MonetarySupervisor interface and use it instead? - make data arg generic bytes? - make collect() run as long as gas provided allows */ contract LoanManager is Restricted { using SafeMath for uint256; uint16 public constant CHUNK_SIZE = 100; enum LoanState { Open, Repaid, Defaulted, Collected } // NB: Defaulted state is not stored, only getters calculate struct LoanProduct { uint minDisbursedAmount; // 0: with decimals set in AugmintToken.decimals uint32 term; // 1 uint32 discountRate; // 2: discountRate in parts per million , ie. 10,000 = 1% uint32 collateralRatio; // 3: loan token amount / colleteral pegged ccy value // in parts per million , ie. 10,000 = 1% uint32 defaultingFeePt; // 4: % of collateral in parts per million , ie. 50,000 = 5% bool isActive; // 5 } /* NB: we don&#39;t need to store loan parameters because loan products can&#39;t be altered (only disabled/enabled) */ struct LoanData { uint collateralAmount; // 0 uint repaymentAmount; // 1 address borrower; // 2 uint32 productId; // 3 LoanState state; // 4 uint40 maturity; // 5 } LoanProduct[] public products; LoanData[] public loans; mapping(address => uint[]) public accountLoans; // owner account address => array of loan Ids Rates public rates; // instance of ETH/pegged currency rate provider contract AugmintTokenInterface public augmintToken; // instance of token contract MonetarySupervisor public monetarySupervisor; event NewLoan(uint32 productId, uint loanId, address indexed borrower, uint collateralAmount, uint loanAmount, uint repaymentAmount, uint40 maturity); event LoanProductActiveStateChanged(uint32 productId, bool newState); event LoanProductAdded(uint32 productId); event LoanRepayed(uint loanId, address borrower); event LoanCollected(uint loanId, address indexed borrower, uint collectedCollateral, uint releasedCollateral, uint defaultingFee); event SystemContractsChanged(Rates newRatesContract, MonetarySupervisor newMonetarySupervisor); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, MonetarySupervisor _monetarySupervisor, Rates _rates) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; monetarySupervisor = _monetarySupervisor; rates = _rates; } function addLoanProduct(uint32 term, uint32 discountRate, uint32 collateralRatio, uint minDisbursedAmount, uint32 defaultingFeePt, bool isActive) external restrict("StabilityBoard") { uint _newProductId = products.push( LoanProduct(minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, isActive) ) - 1; uint32 newProductId = uint32(_newProductId); require(newProductId == _newProductId, "productId overflow"); emit LoanProductAdded(newProductId); } function setLoanProductActiveState(uint32 productId, bool newState) external restrict ("StabilityBoard") { require(productId < products.length, "invalid productId"); // next line would revert but require to emit reason products[productId].isActive = false; emit LoanProductActiveStateChanged(productId, newState); } function newEthBackedLoan(uint32 productId) external payable { require(productId < products.length, "invalid productId"); // next line would revert but require to emit reason LoanProduct storage product = products[productId]; require(product.isActive, "product must be in active state"); // valid product // calculate loan values based on ETH sent in with Tx uint tokenValue = rates.convertFromWei(augmintToken.peggedSymbol(), msg.value); uint repaymentAmount = tokenValue.mul(product.collateralRatio).div(1000000); uint loanAmount; (loanAmount, ) = calculateLoanValues(product, repaymentAmount); require(loanAmount >= product.minDisbursedAmount, "loanAmount must be >= minDisbursedAmount"); uint expiration = now.add(product.term); uint40 maturity = uint40(expiration); require(maturity == expiration, "maturity overflow"); // Create new loan uint loanId = loans.push(LoanData(msg.value, repaymentAmount, msg.sender, productId, LoanState.Open, maturity)) - 1; // Store ref to new loan accountLoans[msg.sender].push(loanId); // Issue tokens and send to borrower monetarySupervisor.issueLoan(msg.sender, loanAmount); emit NewLoan(productId, loanId, msg.sender, msg.value, loanAmount, repaymentAmount, maturity); } /* repay loan, called from AugmintToken&#39;s transferAndNotify Flow for repaying loan: 1) user calls token contract&#39;s transferAndNotify loanId passed in data arg 2) transferAndNotify transfers tokens to the Lender contract 3) transferAndNotify calls Lender.transferNotification with lockProductId */ // from arg is not used as we allow anyone to repay a loan: function transferNotification(address, uint repaymentAmount, uint loanId) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); _repayLoan(loanId, repaymentAmount); } function collect(uint[] loanIds) external { /* when there are a lots of loans to be collected then the client need to call it in batches to make sure tx won&#39;t exceed block gas limit. Anyone can call it - can&#39;t cause harm as it only allows to collect loans which they are defaulted TODO: optimise defaulting fee calculations */ uint totalLoanAmountCollected; uint totalCollateralToCollect; uint totalDefaultingFee; for (uint i = 0; i < loanIds.length; i++) { require(i < loans.length, "invalid loanId"); // next line would revert but require to emit reason LoanData storage loan = loans[loanIds[i]]; require(loan.state == LoanState.Open, "loan state must be Open"); require(now >= loan.maturity, "current time must be later than maturity"); LoanProduct storage product = products[loan.productId]; uint loanAmount; (loanAmount, ) = calculateLoanValues(product, loan.repaymentAmount); totalLoanAmountCollected = totalLoanAmountCollected.add(loanAmount); loan.state = LoanState.Collected; // send ETH collateral to augmintToken reserve uint defaultingFeeInToken = loan.repaymentAmount.mul(product.defaultingFeePt).div(1000000); uint defaultingFee = rates.convertToWei(augmintToken.peggedSymbol(), defaultingFeeInToken); uint targetCollection = rates.convertToWei(augmintToken.peggedSymbol(), loan.repaymentAmount).add(defaultingFee); uint releasedCollateral; if (targetCollection < loan.collateralAmount) { releasedCollateral = loan.collateralAmount.sub(targetCollection); loan.borrower.transfer(releasedCollateral); } uint collateralToCollect = loan.collateralAmount.sub(releasedCollateral); if (defaultingFee >= collateralToCollect) { defaultingFee = collateralToCollect; collateralToCollect = 0; } else { collateralToCollect = collateralToCollect.sub(defaultingFee); } totalDefaultingFee = totalDefaultingFee.add(defaultingFee); totalCollateralToCollect = totalCollateralToCollect.add(collateralToCollect); emit LoanCollected(loanIds[i], loan.borrower, collateralToCollect.add(defaultingFee), releasedCollateral, defaultingFee); } if (totalCollateralToCollect > 0) { address(monetarySupervisor.augmintReserves()).transfer(totalCollateralToCollect); } if (totalDefaultingFee > 0){ address(augmintToken.feeAccount()).transfer(totalDefaultingFee); } monetarySupervisor.loanCollectionNotification(totalLoanAmountCollected);// update KPIs } /* to allow upgrade of Rates and MonetarySupervisor contracts */ function setSystemContracts(Rates newRatesContract, MonetarySupervisor newMonetarySupervisor) external restrict("StabilityBoard") { rates = newRatesContract; monetarySupervisor = newMonetarySupervisor; emit SystemContractsChanged(newRatesContract, newMonetarySupervisor); } function getProductCount() external view returns (uint ct) { return products.length; } // returns CHUNK_SIZE loan products starting from some offset: // [ productId, minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, maxLoanAmount, isActive ] function getProducts(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= products.length) { break; } LoanProduct storage product = products[offset + i]; response[i] = [offset + i, product.minDisbursedAmount, product.term, product.discountRate, product.collateralRatio, product.defaultingFeePt, monetarySupervisor.getMaxLoanAmount(product.minDisbursedAmount), product.isActive ? 1 : 0 ]; } } function getLoanCount() external view returns (uint ct) { return loans.length; } /* returns CHUNK_SIZE loans starting from some offset. Loans data encoded as: [loanId, collateralAmount, repaymentAmount, borrower, productId, state, maturity, disbursementTime, loanAmount, interestAmount ] */ function getLoans(uint offset) external view returns (uint[10][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= loans.length) { break; } response[i] = getLoanTuple(offset + i); } } function getLoanCountForAddress(address borrower) external view returns (uint) { return accountLoans[borrower].length; } /* returns CHUNK_SIZE loans of a given account, starting from some offset. Loans data encoded as: [loanId, collateralAmount, repaymentAmount, borrower, productId, state, maturity, disbursementTime, loanAmount, interestAmount ] */ function getLoansForAddress(address borrower, uint offset) external view returns (uint[10][CHUNK_SIZE] response) { uint[] storage loansForAddress = accountLoans[borrower]; for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= loansForAddress.length) { break; } response[i] = getLoanTuple(loansForAddress[offset + i]); } } function getLoanTuple(uint loanId) public view returns (uint[10] result) { require(loanId < loans.length, "invalid loanId"); // next line would revert but require to emit reason LoanData storage loan = loans[loanId]; LoanProduct storage product = products[loan.productId]; uint loanAmount; uint interestAmount; (loanAmount, interestAmount) = calculateLoanValues(product, loan.repaymentAmount); uint disbursementTime = loan.maturity - product.term; LoanState loanState = loan.state == LoanState.Open && now >= loan.maturity ? LoanState.Defaulted : loan.state; result = [loanId, loan.collateralAmount, loan.repaymentAmount, uint(loan.borrower), loan.productId, uint(loanState), loan.maturity, disbursementTime, loanAmount, interestAmount]; } function calculateLoanValues(LoanProduct storage product, uint repaymentAmount) internal view returns (uint loanAmount, uint interestAmount) { // calculate loan values based on repayment amount loanAmount = repaymentAmount.mul(product.discountRate).div(1000000); interestAmount = loanAmount > repaymentAmount ? 0 : repaymentAmount.sub(loanAmount); } /* internal function, assuming repayment amount already transfered */ function _repayLoan(uint loanId, uint repaymentAmount) internal { require(loanId < loans.length, "invalid loanId"); // next line would revert but require to emit reason LoanData storage loan = loans[loanId]; require(loan.state == LoanState.Open, "loan state must be Open"); require(repaymentAmount == loan.repaymentAmount, "repaymentAmount must be equal to tokens sent"); require(now <= loan.maturity, "current time must be earlier than maturity"); LoanProduct storage product = products[loan.productId]; uint loanAmount; uint interestAmount; (loanAmount, interestAmount) = calculateLoanValues(product, loan.repaymentAmount); loans[loanId].state = LoanState.Repaid; if (interestAmount > 0) { augmintToken.transfer(monetarySupervisor.interestEarnedAccount(), interestAmount); augmintToken.burn(loanAmount); } else { // negative or zero interest (i.e. discountRate >= 0) augmintToken.burn(repaymentAmount); } monetarySupervisor.loanRepaymentNotification(loanAmount); // update KPIs loan.borrower.transfer(loan.collateralAmount); // send back ETH collateral emit LoanRepayed(loanId, loan.borrower); } } /* contract for tracking locked funds requirements -> lock funds -> unlock funds -> index locks by address For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/lockFlow.png TODO / think about: -> self-destruct function? */ contract Locker is Restricted, TokenReceiver { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; event NewLockProduct(uint32 indexed lockProductId, uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive); event LockProductActiveChange(uint32 indexed lockProductId, bool newActiveState); // NB: amountLocked includes the original amount, plus interest event NewLock(address indexed lockOwner, uint lockId, uint amountLocked, uint interestEarned, uint40 lockedUntil, uint32 perTermInterest, uint32 durationInSecs); event LockReleased(address indexed lockOwner, uint lockId); event MonetarySupervisorChanged(MonetarySupervisor newMonetarySupervisor); struct LockProduct { // perTermInterest is in millionths (i.e. 1,000,000 = 100%): uint32 perTermInterest; uint32 durationInSecs; uint32 minimumLockAmount; bool isActive; } /* NB: we don&#39;t need to store lock parameters because lockProducts can&#39;t be altered (only disabled/enabled) */ struct Lock { uint amountLocked; address owner; uint32 productId; uint40 lockedUntil; bool isActive; } AugmintTokenInterface public augmintToken; MonetarySupervisor public monetarySupervisor; LockProduct[] public lockProducts; Lock[] public locks; // lock ids for an account mapping(address => uint[]) public accountLocks; constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, MonetarySupervisor _monetarySupervisor) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; monetarySupervisor = _monetarySupervisor; } function addLockProduct(uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive) external restrict("StabilityBoard") { uint _newLockProductId = lockProducts.push( LockProduct(perTermInterest, durationInSecs, minimumLockAmount, isActive)) - 1; uint32 newLockProductId = uint32(_newLockProductId); require(newLockProductId == _newLockProductId, "lockProduct overflow"); emit NewLockProduct(newLockProductId, perTermInterest, durationInSecs, minimumLockAmount, isActive); } function setLockProductActiveState(uint32 lockProductId, bool isActive) external restrict("StabilityBoard") { // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); lockProducts[lockProductId].isActive = isActive; emit LockProductActiveChange(lockProductId, isActive); } /* lock funds, called from AugmintToken&#39;s transferAndNotify Flow for locking tokens: 1) user calls token contract&#39;s transferAndNotify lockProductId passed in data arg 2) transferAndNotify transfers tokens to the Lock contract 3) transferAndNotify calls Lock.transferNotification with lockProductId */ function transferNotification(address from, uint256 amountToLock, uint _lockProductId) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); uint32 lockProductId = uint32(_lockProductId); require(lockProductId == _lockProductId, "lockProductId overflow"); /* TODO: make data arg generic bytes uint productId; assembly { // solhint-disable-line no-inline-assembly productId := mload(data) } */ _createLock(lockProductId, from, amountToLock); } function releaseFunds(uint lockId) external { // next line would revert but require to emit reason: require(lockId < locks.length, "invalid lockId"); Lock storage lock = locks[lockId]; LockProduct storage lockProduct = lockProducts[lock.productId]; require(lock.isActive, "lock must be in active state"); require(now >= lock.lockedUntil, "current time must be later than lockedUntil"); lock.isActive = false; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); monetarySupervisor.releaseFundsNotification(lock.amountLocked); // to maintain totalLockAmount augmintToken.transferWithNarrative(lock.owner, lock.amountLocked.add(interestEarned), "Funds released from lock"); emit LockReleased(lock.owner, lockId); } function setMonetarySupervisor(MonetarySupervisor newMonetarySupervisor) external restrict("StabilityBoard") { monetarySupervisor = newMonetarySupervisor; emit MonetarySupervisorChanged(newMonetarySupervisor); } function getLockProductCount() external view returns (uint) { return lockProducts.length; } // returns 20 lock products starting from some offset // lock products are encoded as [ perTermInterest, durationInSecs, minimumLockAmount, maxLockAmount, isActive ] function getLockProducts(uint offset) external view returns (uint[5][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= lockProducts.length) { break; } LockProduct storage lockProduct = lockProducts[offset + i]; response[i] = [ lockProduct.perTermInterest, lockProduct.durationInSecs, lockProduct.minimumLockAmount, monetarySupervisor.getMaxLockAmount(lockProduct.minimumLockAmount, lockProduct.perTermInterest), lockProduct.isActive ? 1 : 0 ]; } } function getLockCount() external view returns (uint) { return locks.length; } function getLockCountForAddress(address lockOwner) external view returns (uint) { return accountLocks[lockOwner].length; } // returns CHUNK_SIZE locks starting from some offset // lock products are encoded as // [lockId, owner, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] // NB: perTermInterest is in millionths (i.e. 1,000,000 = 100%): function getLocks(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locks.length) { break; } Lock storage lock = locks[offset + i]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [uint(offset + i), uint(lock.owner), lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0]; } } // returns CHUNK_SIZE locks of a given account, starting from some offset // lock products are encoded as // [lockId, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] function getLocksForAddress(address lockOwner, uint offset) external view returns (uint[7][CHUNK_SIZE] response) { uint[] storage locksForAddress = accountLocks[lockOwner]; for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locksForAddress.length) { break; } Lock storage lock = locks[locksForAddress[offset + i]]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [ locksForAddress[offset + i], lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0 ]; } } function calculateInterest(uint32 perTermInterest, uint amountToLock) public pure returns (uint interestEarned) { interestEarned = amountToLock.mul(perTermInterest).div(1000000); } // Internal function. assumes amountToLock is already transferred to this Lock contract function _createLock(uint32 lockProductId, address lockOwner, uint amountToLock) internal returns(uint lockId) { LockProduct storage lockProduct = lockProducts[lockProductId]; require(lockProduct.isActive, "lockProduct must be in active state"); require(amountToLock >= lockProduct.minimumLockAmount, "amountToLock must be >= minimumLockAmount"); uint interestEarned = calculateInterest(lockProduct.perTermInterest, amountToLock); uint expiration = now.add(lockProduct.durationInSecs); uint40 lockedUntil = uint40(expiration); require(lockedUntil == expiration, "lockedUntil overflow"); lockId = locks.push(Lock(amountToLock, lockOwner, lockProductId, lockedUntil, true)) - 1; accountLocks[lockOwner].push(lockId); monetarySupervisor.requestInterest(amountToLock, interestEarned); // update KPIs & transfer interest here emit NewLock(lockOwner, lockId, amountToLock, interestEarned, lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs); } }
returns CHUNK_SIZE loan products starting from some offset: [ productId, minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, maxLoanAmount, isActive ]
function getProducts(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { LoanProduct storage product = products[offset + i]; response[i] = [offset + i, product.minDisbursedAmount, product.term, product.discountRate, product.collateralRatio, product.defaultingFeePt, monetarySupervisor.getMaxLoanAmount(product.minDisbursedAmount), product.isActive ? 1 : 0 ]; } }
7,655,389
[ 1, 6154, 28096, 67, 4574, 28183, 10406, 5023, 628, 2690, 1384, 30, 306, 23820, 16, 1131, 1669, 70, 295, 730, 6275, 16, 2481, 16, 12137, 4727, 16, 4508, 2045, 287, 8541, 16, 805, 310, 14667, 16484, 16, 943, 1504, 304, 6275, 16, 15083, 308, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15880, 87, 12, 11890, 1384, 13, 3903, 1476, 1135, 261, 11890, 63, 28, 6362, 26464, 67, 4574, 65, 766, 13, 288, 203, 203, 3639, 364, 261, 11890, 2313, 277, 273, 374, 31, 277, 411, 28096, 67, 4574, 31, 277, 27245, 288, 203, 203, 203, 5411, 3176, 304, 4133, 2502, 3017, 273, 10406, 63, 3348, 397, 277, 15533, 203, 203, 5411, 766, 63, 77, 65, 273, 306, 3348, 397, 277, 16, 3017, 18, 1154, 1669, 70, 295, 730, 6275, 16, 3017, 18, 6408, 16, 3017, 18, 23650, 4727, 16, 203, 18701, 3017, 18, 12910, 2045, 287, 8541, 16, 3017, 18, 1886, 310, 14667, 16484, 16, 203, 18701, 31198, 8051, 10227, 18, 588, 2747, 1504, 304, 6275, 12, 5896, 18, 1154, 1669, 70, 295, 730, 6275, 3631, 3017, 18, 291, 3896, 692, 404, 294, 374, 308, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//File: contracts/lib/ens/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) constant returns (address); function resolver(bytes32 _node) constant returns (address); function ttl(bytes32 _node) constant returns (uint64); function setOwner(bytes32 _node, address _owner); function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner); function setResolver(bytes32 _node, address _resolver); function setTTL(bytes32 _node, uint64 _ttl); // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } //File: contracts/lib/ens/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) constant returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) { records[node].text[key] = value; TextChanged(node, key, key); } } //File: contracts/ens/ENSConstants.sol pragma solidity ^0.4.18; contract ENSConstants { bytes32 constant public ENS_ROOT = bytes32(0); bytes32 constant public ETH_TLD_LABEL = keccak256("eth"); bytes32 constant public ETH_TLD_NODE = keccak256(ENS_ROOT, ETH_TLD_LABEL); bytes32 constant public PUBLIC_RESOLVER_LABEL = keccak256("resolver"); bytes32 constant public PUBLIC_RESOLVER_NODE = keccak256(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL); } //File: contracts/acl/IACL.sol pragma solidity ^0.4.18; interface IACL { function initialize(address permissionsCreator) public; function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } //File: contracts/kernel/IKernel.sol pragma solidity ^0.4.18; interface IKernel { event SetApp(bytes32 indexed namespace, bytes32 indexed name, bytes32 indexed id, address app); function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 name, address app) public returns (bytes32 id); function getApp(bytes32 id) public view returns (address); } //File: contracts/apps/AppStorage.sol pragma solidity ^0.4.18; contract AppStorage { IKernel public kernel; bytes32 public appId; address internal pinnedCode; // used by Proxy Pinned uint256 internal initializationBlock; // used by Initializable uint256[95] private storageOffset; // forces App storage to start at after 100 slots uint256 private offset; } //File: contracts/common/Initializable.sol pragma solidity ^0.4.18; contract Initializable is AppStorage { modifier onlyInit { require(initializationBlock == 0); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { initializationBlock = getBlockNumber(); } /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } } //File: contracts/evmscript/IEVMScriptExecutor.sol pragma solidity ^0.4.18; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); } //File: contracts/evmscript/IEVMScriptRegistry.sol pragma solidity 0.4.18; contract EVMScriptRegistryConstants { bytes32 constant public EVMSCRIPT_REGISTRY_APP_ID = keccak256("evmreg.aragonpm.eth"); bytes32 constant public EVMSCRIPT_REGISTRY_APP = keccak256(keccak256("app"), EVMSCRIPT_REGISTRY_APP_ID); } interface IEVMScriptRegistry { function addScriptExecutor(address executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; function getScriptExecutor(bytes script) public view returns (address); } //File: contracts/evmscript/ScriptHelpers.sol pragma solidity 0.4.18; library ScriptHelpers { // To test with JS and compare with actual encoder. Maintaining for reference. // t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) } // run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log(a.slice(2).match(/.{1,64}/g)) ) }) } // This is truly not beautiful but lets no daydream to the day solidity gets reflection features function abiEncode(bytes _a, bytes _b, address[] _c) public pure returns (bytes d) { return encode(_a, _b, _c); } function encode(bytes memory _a, bytes memory _b, address[] memory _c) internal pure returns (bytes memory d) { // A is positioned after the 3 position words uint256 aPosition = 0x60; uint256 bPosition = aPosition + 32 * abiLength(_a); uint256 cPosition = bPosition + 32 * abiLength(_b); uint256 length = cPosition + 32 * abiLength(_c); d = new bytes(length); assembly { // Store positions mstore(add(d, 0x20), aPosition) mstore(add(d, 0x40), bPosition) mstore(add(d, 0x60), cPosition) } // Copy memory to correct position copy(d, getPtr(_a), aPosition, _a.length); copy(d, getPtr(_b), bPosition, _b.length); copy(d, getPtr(_c), cPosition, _c.length * 32); // 1 word per address } function abiLength(bytes memory _a) internal pure returns (uint256) { // 1 for length + // memory words + 1 if not divisible for 32 to offset word return 1 + (_a.length / 32) + (_a.length % 32 > 0 ? 1 : 0); } function abiLength(address[] _a) internal pure returns (uint256) { // 1 for length + 1 per item return 1 + _a.length; } function copy(bytes _d, uint256 _src, uint256 _pos, uint256 _length) internal pure { uint dest; assembly { dest := add(add(_d, 0x20), _pos) } memcpy(dest, _src, _length + 32); } function getPtr(bytes memory _x) internal pure returns (uint256 ptr) { assembly { ptr := _x } } function getPtr(address[] memory _x) internal pure returns (uint256 ptr) { assembly { ptr := _x } } function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); payload[0] = bytes1(_sig); payload[1] = bytes1(_sig << 8); payload[2] = bytes1(_sig << 16); payload[3] = bytes1(_sig << 24); return payload; } function memcpy(uint _dest, uint _src, uint _len) public pure { uint256 src = _src; uint256 dest = _dest; uint256 len = _len; // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } //File: contracts/evmscript/EVMScriptRunner.sol pragma solidity ^0.4.18; contract EVMScriptRunner is AppStorage, EVMScriptRegistryConstants { using ScriptHelpers for bytes; function runScript(bytes _script, bytes _input, address[] _blacklist) protectState internal returns (bytes output) { // TODO: Too much data flying around, maybe extracting spec id here is cheaper address executorAddr = getExecutor(_script); require(executorAddr != address(0)); bytes memory calldataArgs = _script.encode(_input, _blacklist); bytes4 sig = IEVMScriptExecutor(0).execScript.selector; require(executorAddr.delegatecall(sig, calldataArgs)); return returnedDataDecoded(); } function getExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getExecutorRegistry().getScriptExecutor(_script)); } // TODO: Internal function getExecutorRegistry() internal view returns (IEVMScriptRegistry) { address registryAddr = kernel.getApp(EVMSCRIPT_REGISTRY_APP); return IEVMScriptRegistry(registryAddr); } /** * @dev copies and returns last's call data. Needs to ABI decode first */ function returnedDataDecoded() internal view returns (bytes ret) { assembly { let size := returndatasize switch size case 0 {} default { ret := mload(0x40) // free mem ptr get mstore(0x40, add(ret, add(size, 0x20))) // free mem ptr set returndatacopy(ret, 0x20, sub(size, 0x20)) // copy return data } } return ret; } modifier protectState { address preKernel = kernel; bytes32 preAppId = appId; _; // exec require(kernel == preKernel); require(appId == preAppId); } } //File: contracts/acl/ACLSyntaxSugar.sol pragma solidity 0.4.18; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[] r) {} function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } //File: contracts/apps/AragonApp.sol pragma solidity ^0.4.18; contract AragonApp is AppStorage, Initializable, ACLSyntaxSugar, EVMScriptRunner { modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0))); _; } modifier authP(bytes32 _role, uint256[] params) { require(canPerform(msg.sender, _role, params)); _; } function canPerform(address _sender, bytes32 _role, uint256[] params) public view returns (bool) { bytes memory how; // no need to init memory as it is never used if (params.length > 0) { uint256 byteLength = params.length * 32; assembly { how := params // forced casting mstore(how, byteLength) } } return address(kernel) == 0 || kernel.hasPermission(_sender, address(this), _role, how); } } //File: contracts/ens/ENSSubdomainRegistrar.sol pragma solidity 0.4.18; contract ENSSubdomainRegistrar is AragonApp, ENSConstants { bytes32 constant public CREATE_NAME_ROLE = bytes32(1); bytes32 constant public DELETE_NAME_ROLE = bytes32(2); bytes32 constant public POINT_ROOTNODE_ROLE = bytes32(3); AbstractENS public ens; bytes32 public rootNode; event NewName(bytes32 indexed node, bytes32 indexed label); event DeleteName(bytes32 indexed node, bytes32 indexed label); function initialize(AbstractENS _ens, bytes32 _rootNode) onlyInit public { initialized(); // We need ownership to create subnodes require(_ens.owner(_rootNode) == address(this)); ens = _ens; rootNode = _rootNode; } function createName(bytes32 _label, address _owner) auth(CREATE_NAME_ROLE) external returns (bytes32 node) { return _createName(_label, _owner); } function createNameAndPoint(bytes32 _label, address _target) auth(CREATE_NAME_ROLE) external returns (bytes32 node) { node = _createName(_label, this); _pointToResolverAndResolve(node, _target); } function deleteName(bytes32 _label) auth(DELETE_NAME_ROLE) external { bytes32 node = keccak256(rootNode, _label); address currentOwner = ens.owner(node); require(currentOwner != address(0)); // fail if deleting unset name if (currentOwner != address(this)) { // needs to reclaim ownership so it can set resolver ens.setSubnodeOwner(rootNode, _label, this); } ens.setResolver(node, address(0)); // remove resolver so it ends resolving ens.setOwner(node, address(0)); DeleteName(node, _label); } function pointRootNode(address _target) auth(POINT_ROOTNODE_ROLE) external { _pointToResolverAndResolve(rootNode, _target); } function _createName(bytes32 _label, address _owner) internal returns (bytes32 node) { node = keccak256(rootNode, _label); require(ens.owner(node) == address(0)); // avoid name reset ens.setSubnodeOwner(rootNode, _label, _owner); NewName(node, _label); } function _pointToResolverAndResolve(bytes32 _node, address _target) internal { address publicResolver = getAddr(PUBLIC_RESOLVER_NODE); ens.setResolver(_node, publicResolver); PublicResolver(publicResolver).setAddr(_node, _target); } function getAddr(bytes32 node) internal view returns (address) { address resolver = ens.resolver(node); return PublicResolver(resolver).addr(node); } } //File: contracts/apps/IAppProxy.sol pragma solidity 0.4.18; interface IAppProxy { function isUpgradeable() public pure returns (bool); function getCode() public view returns (address); } //File: contracts/common/DelegateProxy.sol pragma solidity 0.4.18; contract DelegateProxy { /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); assembly { let result := delegatecall(sub(gas, 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function isContract(address _target) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } //File: contracts/kernel/KernelStorage.sol pragma solidity 0.4.18; contract KernelConstants { bytes32 constant public CORE_NAMESPACE = keccak256("core"); bytes32 constant public APP_BASES_NAMESPACE = keccak256("base"); bytes32 constant public APP_ADDR_NAMESPACE = keccak256("app"); bytes32 constant public KERNEL_APP_ID = keccak256("kernel.aragonpm.eth"); bytes32 constant public KERNEL_APP = keccak256(CORE_NAMESPACE, KERNEL_APP_ID); bytes32 constant public ACL_APP_ID = keccak256("acl.aragonpm.eth"); bytes32 constant public ACL_APP = keccak256(APP_ADDR_NAMESPACE, ACL_APP_ID); } contract KernelStorage is KernelConstants { mapping (bytes32 => address) public apps; } //File: contracts/apps/AppProxyBase.sol pragma solidity 0.4.18; contract AppProxyBase is IAppProxy, AppStorage, DelegateProxy, KernelConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ function AppProxyBase(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { kernel = _kernel; appId = _appId; // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel.getApp(keccak256(APP_BASES_NAMESPACE, _appId)); } function () payable public { address target = getCode(); require(target != 0); // if app code hasn't been set yet, don't call delegatedFwd(target, msg.data); } } //File: contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.18; contract AppProxyUpgradeable is AppProxyBase { address public pinnedCode; /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ function AppProxyUpgradeable(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public { } function getCode() public view returns (address) { return getAppBase(appId); } function isUpgradeable() public pure returns (bool) { return true; } } //File: contracts/apps/AppProxyPinned.sol pragma solidity 0.4.18; contract AppProxyPinned is AppProxyBase { /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ function AppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public { pinnedCode = getAppBase(appId); require(pinnedCode != address(0)); } function getCode() public view returns (address) { return pinnedCode; } function isUpgradeable() public pure returns (bool) { return false; } function () payable public { delegatedFwd(getCode(), msg.data); } } //File: contracts/factory/AppProxyFactory.sol pragma solidity 0.4.18; contract AppProxyFactory { event NewAppProxy(address proxy); function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); NewAppProxy(address(proxy)); return proxy; } function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); NewAppProxy(address(proxy)); return proxy; } } //File: contracts/acl/ACL.sol pragma solidity 0.4.18; interface ACLOracle { function canPerform(address who, address where, bytes32 what) public view returns (bool); } contract ACL is IACL, AragonApp, ACLHelpers { bytes32 constant public CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); // whether a certain entity has a permission mapping (bytes32 => bytes32) permissions; // 0 for no permission, or parameters id mapping (bytes32 => Param[]) public permissionParams; // who is the manager of a permission mapping (bytes32 => address) permissionManager; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, NOT, AND, OR, XOR, IF_ELSE, RET } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 constant BLOCK_NUMBER_PARAM_ID = 200; uint8 constant TIMESTAMP_PARAM_ID = 201; uint8 constant SENDER_PARAM_ID = 202; uint8 constant ORACLE_PARAM_ID = 203; uint8 constant LOGIC_OP_PARAM_ID = 204; uint8 constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? bytes32 constant public EMPTY_PARAM_HASH = keccak256(uint256(0)); address constant ANY_ENTITY = address(-1); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role)); _; } event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initializes an ACL instance and sets `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) onlyInit public { initialized(); require(msg.sender == address(kernel)); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set. Access is limited by the ACL. * If a created permission is removed it is possible to reset it with createPermission. * @notice Create a new permission granting `_entity` the ability to perform actions of role `_role` on `_app` (setting `_manager` as the permission manager) * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external { require(hasPermission(msg.sender, address(this), CREATE_PERMISSIONS_ROLE)); _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grants `_entity` the ability to perform actions of role `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grants `_entity` the ability to perform actions of role `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) onlyPermissionManager(_app, _role) public { require(!hasPermission(_entity, _app, _role)); bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revokes `_entity` the ability to perform actions of role `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) onlyPermissionManager(_app, _role) external { require(hasPermission(_entity, _app, _role)); _setPermission(_entity, _app, _role, bytes32(0)); } /** * @notice Sets `_newManager` as the manager of the permission `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) onlyPermissionManager(_app, _role) external { _setPermissionManager(_newManager, _app, _role); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { uint256[] memory how; uint256 intsLength = _how.length / 32; assembly { how := _how // forced casting mstore(how, intsLength) } // _how is invalid from this point fwd return hasPermission(_who, _where, _what, how); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != bytes32(0) && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != bytes32(0) && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0)); _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; SetPermission(_entity, _app, _role, _paramsHash != bytes32(0)); } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(_encodedParams); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return evalParam(_paramsHash, 0, _who, _where, _what, _how); } function evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = ACLOracle(param.value).canPerform(_who, _where, _what) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = blockN(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = time(); } else if (param.id == SENDER_PARAM_ID) { value = uint256(msg.sender); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { var (condition, success, failure) = decodeParamsList(uint256(_param.value)); bool result = evalParam(_paramsHash, condition, _who, _where, _what, _how); return evalParam(_paramsHash, result ? success : failure, _who, _where, _what, _how); } var (v1, v2,) = decodeParamsList(uint256(_param.value)); bool r1 = evalParam(_paramsHash, v1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = evalParam(_paramsHash, v2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return (r1 && !r2) || (!r1 && r2); } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) pure internal returns (bytes32) { return keccak256(uint256(1), _where, _what); } function permissionHash(address _who, address _where, bytes32 _what) pure internal returns (bytes32) { return keccak256(uint256(2), _who, _where, _what); } function time() internal view returns (uint64) { return uint64(block.timestamp); } // solium-disable-line security/no-block-members function blockN() internal view returns (uint256) { return block.number; } } //File: contracts/apm/Repo.sol pragma solidity ^0.4.15; contract Repo is AragonApp { struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } Version[] versions; mapping (bytes32 => uint256) versionIdForSemantic; mapping (address => uint256) latestVersionIdForContract; bytes32 constant public CREATE_VERSION_ROLE = bytes32(1); event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @notice Create new version for repo * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) auth(CREATE_VERSION_ROLE) public { address contractAddress = _contractAddress; if (versions.length > 0) { Version storage lastVersion = versions[versions.length - 1]; require(isValidBump(lastVersion.semanticVersion, _newSemanticVersion)); if (contractAddress == 0) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require(lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0]); } else { versions.length += 1; uint16[3] memory zeroVersion; require(isValidBump(zeroVersion, _newSemanticVersion)); } uint versionId = versions.push(Version(_newSemanticVersion, contractAddress, _contentURI)) - 1; versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versions.length - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { uint256 len = versions.length; return len > 0 ? len - 1 : 0; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(version[0], version[1], version[2]); } } //File: contracts/apm/APMRegistry.sol pragma solidity 0.4.18; contract APMRegistryConstants { // Cant have a regular APM appId because it is used to build APM // TODO: recheck this string constant public APM_APP_NAME = "apm-registry"; string constant public REPO_APP_NAME = "apm-repo"; string constant public ENS_SUB_APP_NAME = "apm-enssub"; } contract APMRegistry is AragonApp, AppProxyFactory, APMRegistryConstants { AbstractENS ens; ENSSubdomainRegistrar public registrar; bytes32 constant public CREATE_REPO_ROLE = bytes32(1); event NewRepo(bytes32 id, string name, address repo); /** * NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar * @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership */ function initialize(ENSSubdomainRegistrar _registrar) onlyInit public { initialized(); registrar = _registrar; ens = registrar.ens(); registrar.pointRootNode(this); // Check APM has all permissions it needss ACL acl = ACL(kernel.acl()); require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE())); require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE())); } /** * @notice Create new repo in registry with `_name` * @param _name Repo name, must be ununsed * @param _dev Address that will be given permission to create versions */ function newRepo(string _name, address _dev) auth(CREATE_REPO_ROLE) public returns (Repo) { return _newRepo(_name, _dev); } /** * @notice Create new repo in registry with `_name` and first repo version * @param _name Repo name * @param _dev Address that will be given permission to create versions * @param _initialSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newRepoWithVersion( string _name, address _dev, uint16[3] _initialSemanticVersion, address _contractAddress, bytes _contentURI ) auth(CREATE_REPO_ROLE) public returns (Repo) { Repo repo = _newRepo(_name, this); // need to have permissions to create version repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI); // Give permissions to _dev ACL acl = ACL(kernel.acl()); acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE()); acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE()); acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE()); return repo; } function _newRepo(string _name, address _dev) internal returns (Repo) { require(bytes(_name).length > 0); Repo repo = newClonedRepo(); ACL(kernel.acl()).createPermission(_dev, repo, repo.CREATE_VERSION_ROLE(), _dev); // Creates [name] subdomain in the rootNode and sets registry as resolver // This will fail if repo name already exists bytes32 node = registrar.createNameAndPoint(keccak256(_name), repo); NewRepo(node, _name, repo); return repo; } function newClonedRepo() internal returns (Repo) { return Repo(newAppProxy(kernel, repoAppId())); } function repoAppId() internal view returns (bytes32) { return keccak256(registrar.rootNode(), keccak256(REPO_APP_NAME)); } } //File: contracts/kernel/Kernel.sol pragma solidity 0.4.18; contract Kernel is IKernel, KernelStorage, Initializable, AppProxyFactory, ACLSyntaxSugar { bytes32 constant public APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initializes a kernel instance along with its ACL and sets `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _baseAcl, address _permissionsCreator) onlyInit public { initialized(); IACL acl = IACL(newAppProxy(this, ACL_APP_ID)); _setApp(APP_BASES_NAMESPACE, ACL_APP_ID, _baseAcl); _setApp(APP_ADDR_NAMESPACE, ACL_APP_ID, acl); acl.initialize(_permissionsCreator); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @param _name Name of the app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _name, address _appBase) auth(APP_MANAGER_ROLE, arr(APP_BASES_NAMESPACE, _name)) public returns (IAppProxy appProxy) { _setAppIfNew(APP_BASES_NAMESPACE, _name, _appBase); appProxy = newAppProxy(this, _name); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @param _name Name of the app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _name, address _appBase) auth(APP_MANAGER_ROLE, arr(APP_BASES_NAMESPACE, _name)) public returns (IAppProxy appProxy) { _setAppIfNew(APP_BASES_NAMESPACE, _name, _appBase); appProxy = newAppProxyPinned(this, _name); } /** * @dev Set the resolving address of an app instance or base implementation * @param _namespace App namespace to use * @param _name Name of the app * @param _app Address of the app * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _name, address _app) auth(APP_MANAGER_ROLE, arr(_namespace, _name)) kernelIntegrity public returns (bytes32 id) { return _setApp(_namespace, _name, _app); } /** * @dev Get the address of an app instance or base implementation * @param _id App identifier * @return Address of the app */ function getApp(bytes32 _id) public view returns (address) { return apps[_id]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(ACL_APP)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { return acl().hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _name, address _app) internal returns (bytes32 id) { id = keccak256(_namespace, _name); apps[id] = _app; SetApp(_namespace, _name, id, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _name, address _app) internal returns (bytes32 id) { id = keccak256(_namespace, _name); if (_app != address(0)) { address app = getApp(id); if (app != address(0)) { require(app == _app); } else { apps[id] = _app; SetApp(_namespace, _name, id, _app); } } } modifier auth(bytes32 _role, uint256[] memory params) { bytes memory how; uint256 byteLength = params.length * 32; assembly { how := params // forced casting mstore(how, byteLength) } // Params is invalid from this point fwd require(hasPermission(msg.sender, address(this), _role, how)); _; } modifier kernelIntegrity { _; // After execution check integrity address kernel = getApp(KERNEL_APP); uint256 size; assembly { size := extcodesize(kernel) } require(size > 0); } } //File: contracts/kernel/KernelProxy.sol pragma solidity 0.4.18; contract KernelProxy is KernelStorage, DelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ function KernelProxy(address _kernelImpl) public { apps[keccak256(CORE_NAMESPACE, KERNEL_APP_ID)] = _kernelImpl; } /** * @dev All calls made to the proxy are forwarded to the kernel implementation via a delegatecall * @return Any bytes32 value the implementation returns */ function () payable public { delegatedFwd(apps[KERNEL_APP], msg.data); } } //File: contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.18; contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; // WARN: Manager can censor all votes and the like happening in an org bytes32 constant public REGISTRY_MANAGER_ROLE = bytes32(1); struct ExecutorEntry { address executor; bool enabled; } ExecutorEntry[] public executors; function initialize() onlyInit public { initialized(); // Create empty record to begin executor IDs at 1 executors.push(ExecutorEntry(address(0), false)); } function addScriptExecutor(address _executor) external auth(REGISTRY_MANAGER_ROLE) returns (uint id) { return executors.push(ExecutorEntry(_executor, true)); } function disableScriptExecutor(uint256 _executorId) external auth(REGISTRY_MANAGER_ROLE) { executors[_executorId].enabled = false; } function getScriptExecutor(bytes _script) public view returns (address) { uint256 id = _script.getSpecId(); if (id == 0 || id >= executors.length) { return address(0); } ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : address(0); } } //File: contracts/evmscript/executors/CallsScript.sol pragma solidity ^0.4.18; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is IEVMScriptExecutor { using ScriptHelpers for bytes; uint256 constant internal SCRIPT_START_LOCATION = 4; event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _input Input is ignored in callscript * @param _blacklist Addresses the script cannot call to, or will revert. * @return always returns empty byte array */ function execScript(bytes _script, bytes _input, address[] _blacklist) external returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i]); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 calldataStart = _script.locationOf(location + 0x14 + 0x04); assembly { let success := call(sub(gas, 5000), contractAddress, 0, calldataStart, calldataLength, 0, 0) switch success case 0 { revert(0, 0) } } location += (0x14 + 0x04 + calldataLength); } } } //File: contracts/evmscript/executors/DelegateScript.sol pragma solidity 0.4.18; interface DelegateScriptTarget { function exec() public; } contract DelegateScript is IEVMScriptExecutor { using ScriptHelpers for *; uint256 constant internal SCRIPT_START_LOCATION = 4; /** * @notice Executes script by delegatecall into a contract * @param _script [ specId (uint32) ][ contract address (20 bytes) ] * @param _input ABI encoded call to be made to contract (if empty executes default exec() function) * @param _blacklist If any address is passed, will revert. * @return Call return data */ function execScript(bytes _script, bytes _input, address[] _blacklist) external returns (bytes) { require(_blacklist.length == 0); // dont have ability to control bans, so fail. // Script should be spec id + address (20 bytes) require(_script.length == SCRIPT_START_LOCATION + 20); return delegate(_script.addressAt(SCRIPT_START_LOCATION), _input); } /** * @dev Delegatecall to contract with input data */ function delegate(address _addr, bytes memory _input) internal returns (bytes memory output) { require(isContract(_addr)); require(_addr.delegatecall(_input.length > 0 ? _input : defaultInput())); return returnedData(); } function isContract(address _target) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_target) } return size > 0; } function defaultInput() internal pure returns (bytes) { return DelegateScriptTarget(0).exec.selector.toBytes(); } /** * @dev copies and returns last's call data */ function returnedData() internal view returns (bytes ret) { assembly { let size := returndatasize ret := mload(0x40) // free mem ptr get mstore(0x40, add(ret, add(size, 0x20))) // free mem ptr set mstore(ret, size) // set array length returndatacopy(add(ret, 0x20), 0, size) // copy return data } return ret; } } //File: contracts/evmscript/executors/DeployDelegateScript.sol pragma solidity 0.4.18; // Inspired by: https://github.com/dapphub/ds-proxy/blob/master/src/proxy.sol contract DeployDelegateScript is DelegateScript { uint256 constant internal SCRIPT_START_LOCATION = 4; mapping (bytes32 => address) cache; /** * @notice Executes script by delegatecall into a deployed contract (exec() function) * @param _script [ specId (uint32) ][ contractInitcode (bytecode) ] * @param _input ABI encoded call to be made to contract (if empty executes default exec() function) * @param _blacklist If any address is passed, will revert. * @return Call return data */ function execScript(bytes _script, bytes _input, address[] _blacklist) external returns (bytes) { require(_blacklist.length == 0); // dont have ability to control bans, so fail. bytes32 id = keccak256(_script); address deployed = cache[id]; if (deployed == address(0)) { deployed = deploy(_script); cache[id] = deployed; } return DelegateScript.delegate(deployed, _input); } /** * @dev Deploys contract byte code to network */ function deploy(bytes _script) internal returns (address addr) { assembly { // 0x24 = 0x20 (length) + 0x04 (spec id uint32) // Length of code is 4 bytes less than total script size addr := create(0, add(_script, 0x24), sub(mload(_script), 0x04)) switch iszero(extcodesize(addr)) case 1 { revert(0, 0) } // throw if contract failed to deploy } } } //File: contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.18; contract EVMScriptRegistryFactory is AppProxyFactory, EVMScriptRegistryConstants { address public baseReg; address public baseCalls; address public baseDel; address public baseDeployDel; function EVMScriptRegistryFactory() public { baseReg = address(new EVMScriptRegistry()); baseCalls = address(new CallsScript()); baseDel = address(new DelegateScript()); baseDeployDel = address(new DeployDelegateScript()); } function newEVMScriptRegistry(Kernel _dao, address _root) public returns (EVMScriptRegistry reg) { reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg)); reg.initialize(); ACL acl = ACL(_dao.acl()); _dao.setApp(_dao.APP_ADDR_NAMESPACE(), EVMSCRIPT_REGISTRY_APP_ID, reg); acl.createPermission(this, reg, reg.REGISTRY_MANAGER_ROLE(), this); reg.addScriptExecutor(baseCalls); // spec 1 = CallsScript reg.addScriptExecutor(baseDel); // spec 2 = DelegateScript reg.addScriptExecutor(baseDeployDel); // spec 3 = DeployDelegateScript acl.revokePermission(this, reg, reg.REGISTRY_MANAGER_ROLE()); acl.setPermissionManager(_root, reg, reg.REGISTRY_MANAGER_ROLE()); return reg; } } //File: contracts/factory/DAOFactory.sol pragma solidity 0.4.18; contract DAOFactory { address public baseKernel; address public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); function DAOFactory(address _baseKernel, address _baseACL, address _regFactory) public { // No need to init as it cannot be killed by devops199 if (_regFactory != address(0)) { regFactory = EVMScriptRegistryFactory(_regFactory); } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @param _root Address that will be granted control to setup DAO permissions */ function newDAO(address _root) public returns (Kernel dao) { dao = Kernel(new KernelProxy(baseKernel)); address initialRoot = address(regFactory) != address(0) ? this : _root; dao.initialize(baseACL, initialRoot); ACL acl = ACL(dao.acl()); if (address(regFactory) != address(0)) { bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao, _root); DeployEVMScriptRegistry(address(reg)); acl.revokePermission(regFactory, dao, appManagerRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(address(0), dao, appManagerRole); acl.setPermissionManager(_root, acl, permRole); } DeployDAO(dao); } } //File: contracts/lib/ens/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) { NewTTL(node, ttl); records[node].ttl = ttl; } } //File: contracts/factory/ENSFactory.sol pragma solidity 0.4.18; contract ENSFactory is ENSConstants { event DeployENS(address ens); // This is an incredibly trustfull ENS deployment, only use for testing function newENS(address _owner) public returns (ENS ens) { ens = new ENS(); // Setup .eth TLD ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this); // Setup public resolver PublicResolver resolver = new PublicResolver(ens); ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this); ens.setResolver(PUBLIC_RESOLVER_NODE, resolver); resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver); ens.setOwner(ETH_TLD_NODE, _owner); ens.setOwner(ENS_ROOT, _owner); DeployENS(ens); } } //File: contracts/factory/APMRegistryFactory.sol pragma solidity 0.4.18; contract APMRegistryFactory is APMRegistryConstants { DAOFactory public daoFactory; APMRegistry public registryBase; Repo public repoBase; ENSSubdomainRegistrar public ensSubdomainRegistrarBase; ENS public ens; event DeployAPM(bytes32 indexed node, address apm); // Needs either one ENS or ENSFactory function APMRegistryFactory( DAOFactory _daoFactory, APMRegistry _registryBase, Repo _repoBase, ENSSubdomainRegistrar _ensSubBase, ENS _ens, ENSFactory _ensFactory ) public // DAO initialized without evmscript run support { daoFactory = _daoFactory; registryBase = _registryBase; repoBase = _repoBase; ensSubdomainRegistrarBase = _ensSubBase; // Either the ENS address provided is used, if any. // Or we use the ENSFactory to generate a test instance of ENS // If not the ENS address nor factory address are provided, this will revert ens = _ens != address(0) ? _ens : _ensFactory.newENS(this); } function newAPM(bytes32 _tld, bytes32 _label, address _root) public returns (APMRegistry) { bytes32 node = keccak256(_tld, _label); // Assume it is the test ENS if (ens.owner(node) != address(this)) { // If we weren't in test ens and factory doesn't have ownership, will fail ens.setSubnodeOwner(_tld, _label, this); } Kernel dao = daoFactory.newDAO(this); ACL acl = ACL(dao.acl()); acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this); bytes32 namespace = dao.APP_BASES_NAMESPACE(); // Deploy app proxies ENSSubdomainRegistrar ensSub = ENSSubdomainRegistrar(dao.newAppInstance(keccak256(node, keccak256(ENS_SUB_APP_NAME)), ensSubdomainRegistrarBase)); APMRegistry apm = APMRegistry(dao.newAppInstance(keccak256(node, keccak256(APM_APP_NAME)), registryBase)); // APMRegistry controls Repos dao.setApp(namespace, keccak256(node, keccak256(REPO_APP_NAME)), repoBase); DeployAPM(node, apm); // Grant permissions needed for APM on ENSSubdomainRegistrar acl.createPermission(apm, ensSub, ensSub.CREATE_NAME_ROLE(), _root); acl.createPermission(apm, ensSub, ensSub.POINT_ROOTNODE_ROLE(), _root); // allow apm to create permissions for Repos in Kernel bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); acl.grantPermission(apm, acl, permRole); // Initialize ens.setOwner(node, ensSub); ensSub.initialize(ens, node); apm.initialize(ensSub); uint16[3] memory firstVersion; firstVersion[0] = 1; acl.createPermission(this, apm, apm.CREATE_REPO_ROLE(), this); apm.newRepoWithVersion(APM_APP_NAME, _root, firstVersion, registryBase, b("ipfs:apm")); apm.newRepoWithVersion(ENS_SUB_APP_NAME, _root, firstVersion, ensSubdomainRegistrarBase, b("ipfs:enssub")); apm.newRepoWithVersion(REPO_APP_NAME, _root, firstVersion, repoBase, b("ipfs:repo")); configureAPMPermissions(acl, apm, _root); // Permission transition to _root acl.setPermissionManager(_root, dao, dao.APP_MANAGER_ROLE()); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); return apm; } function b(string memory x) internal pure returns (bytes memory y) { y = bytes(x); } // Factory can be subclassed and permissions changed function configureAPMPermissions(ACL _acl, APMRegistry _apm, address _root) internal { _acl.grantPermission(_root, _apm, _apm.CREATE_REPO_ROLE()); _acl.setPermissionManager(_root, _apm, _apm.CREATE_REPO_ROLE()); } }
needs to reclaim ownership so it can set resolver
if (currentOwner != address(this)) {
1,637,485
[ 1, 20600, 358, 283, 14784, 23178, 1427, 518, 848, 444, 5039, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 2972, 5541, 480, 1758, 12, 2211, 3719, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x614775d11B6209FCC12147e111a308eab684E438/sources/AlphaSorbetVault.sol
* @notice Withdraws tokens in proportion to the vault's holdings. @dev Removes proportional amount of liquidity from Uniswap. Note it doesn't collect share of fees since last rebalance to save gas. @param liquidity burned by sender @return amount0 Amount of token0 sent to recipient @return amount1 Amount of token1 sent to recipient/
function withdraw( uint128 liquidity ) external nonReentrant updateVault(msg.sender) returns (uint256 amount0, uint256 amount1) { require(liquidity > 0, "liquidity"); UserInfo storage user = userInfo[msg.sender]; require(user.liquidity >= liquidity, "Sorbetto: you cant eat that much popsicles"); user.liquidity = user.liquidity.sub128(liquidity); totalLiquidity = totalLiquidity.sub128(liquidity); (amount0, amount1) = _burnLiquidityShare(liquidity, msg.sender); emit Withdraw(msg.sender, liquidity, amount0, amount1); }
2,909,689
[ 1, 1190, 9446, 87, 2430, 316, 23279, 358, 326, 9229, 1807, 6887, 899, 18, 225, 20284, 23279, 287, 3844, 434, 4501, 372, 24237, 628, 1351, 291, 91, 438, 18, 3609, 518, 3302, 1404, 3274, 7433, 434, 1656, 281, 3241, 1142, 283, 12296, 358, 1923, 16189, 18, 225, 4501, 372, 24237, 18305, 329, 635, 5793, 327, 3844, 20, 16811, 434, 1147, 20, 3271, 358, 8027, 327, 3844, 21, 16811, 434, 1147, 21, 3271, 358, 8027, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 12, 203, 3639, 2254, 10392, 4501, 372, 24237, 203, 565, 262, 3903, 1661, 426, 8230, 970, 1089, 12003, 12, 3576, 18, 15330, 13, 1135, 261, 11890, 5034, 3844, 20, 16, 2254, 5034, 3844, 21, 13, 288, 203, 3639, 2583, 12, 549, 372, 24237, 405, 374, 16, 315, 549, 372, 24237, 8863, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 549, 372, 24237, 1545, 4501, 372, 24237, 16, 315, 55, 16640, 278, 869, 30, 1846, 848, 88, 20729, 716, 9816, 28518, 8383, 8863, 203, 3639, 729, 18, 549, 372, 24237, 273, 729, 18, 549, 372, 24237, 18, 1717, 10392, 12, 549, 372, 24237, 1769, 203, 3639, 2078, 48, 18988, 24237, 273, 2078, 48, 18988, 24237, 18, 1717, 10392, 12, 549, 372, 24237, 1769, 203, 3639, 261, 8949, 20, 16, 3844, 21, 13, 273, 389, 70, 321, 48, 18988, 24237, 9535, 12, 549, 372, 24237, 16, 1234, 18, 15330, 1769, 203, 540, 203, 540, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 4501, 372, 24237, 16, 3844, 20, 16, 3844, 21, 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 ]
./partial_match/4/0x3C15CAC28a7a35eFCE63205556139bc0240ece64/sources/DF9.sol
URI's default URI prefix
contract ERC1155Metadata is IERC1155Metadata { string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); | Metadata Public Function s | |__________________________________*/ pragma solidity ^0.6.0; function uri(uint256 _id) public override view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } |__________________________________*/ | Metadata Internal Functions | function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } |__________________________________*/ | Utility Internal Functions | function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } } function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } } function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } } function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } } return string(bstr); }
8,774,168
[ 1, 3098, 1807, 805, 3699, 1633, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4232, 39, 2499, 2539, 2277, 353, 467, 654, 39, 2499, 2539, 2277, 288, 203, 203, 225, 533, 2713, 1026, 2277, 3098, 31, 203, 225, 871, 3699, 12, 1080, 389, 1650, 16, 2254, 5034, 8808, 389, 350, 1769, 203, 203, 203, 225, 571, 377, 6912, 7224, 4284, 272, 565, 571, 203, 225, 571, 21157, 21157, 972, 5549, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 225, 445, 2003, 12, 11890, 5034, 389, 350, 13, 1071, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 565, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 2277, 3098, 16, 389, 11890, 22, 701, 24899, 350, 3631, 3552, 1977, 7923, 1769, 203, 225, 289, 203, 203, 203, 225, 571, 21157, 21157, 972, 5549, 203, 203, 225, 571, 565, 6912, 3186, 15486, 565, 571, 203, 225, 445, 389, 1330, 1099, 2520, 12, 11890, 5034, 8526, 3778, 389, 2316, 5103, 13, 2713, 288, 203, 565, 533, 3778, 17480, 273, 1026, 2277, 3098, 31, 203, 565, 533, 3778, 1147, 3098, 31, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 2316, 5103, 18, 2469, 31, 277, 27245, 288, 203, 1377, 1147, 3098, 273, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 1785, 16, 389, 11890, 22, 701, 24899, 2316, 5103, 63, 77, 65, 3631, 3552, 1977, 7923, 1769, 203, 1377, 3626, 3699, 12, 2316, 3098, 16, 389, 2316, 5103, 63, 77, 19226, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 389, 1330, 1099, 2520, 2 ]
./partial_match/42/0x0DCFB96461f639d3a9b89f56A7438030DCA7f80E/sources/MockPool.sol
get reward token address
function getToken() public view returns(address) { return token; }
3,440,783
[ 1, 588, 19890, 1147, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9162, 1435, 1071, 1476, 1135, 12, 2867, 13, 288, 203, 3639, 327, 1147, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ITreasury.sol"; import "../utils/ContractGuard.sol"; import "../Authorizable.sol"; // Note that this pool has no minter key of GAME (rewards). // Instead, the governance will call GAME distributeReward method and send reward to this pool at the beginning. contract GameGenesisRewardPool is Authorizable, ContractGuard { using SafeMath for uint256; using SafeERC20 for IERC20; ITreasury public treasury; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. GAME to distribute. uint256 lastRewardTime; // Last time that GAME distribution occurs. uint256 accGamePerShare; // Accumulated GAME per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } IERC20 public game; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The time when GAME mining starts. uint256 public poolStartTime; // The time when GAME mining ends. uint256 public poolEndTime; // MAINNET uint256 public gamePerSecond = 0.09645 ether; // Approximately 25000 GAME / (72h * 60min * 60s) uint256 public runningTime = 3 days; // 3 days uint256 public depositFee = 100; // END MAINNET event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 amount); constructor( address _game, ITreasury _treasury, uint256 _poolStartTime ) public { require(block.timestamp < _poolStartTime, "late"); if (_game != address(0)) game = IERC20(_game); treasury = _treasury; poolStartTime = _poolStartTime; poolEndTime = poolStartTime + runningTime; } // Allow us to delay or begin earlier if we have not started yet. Careful of gas. function setPoolStartTime( uint256 _time ) public onlyAuthorized { require(block.timestamp < poolStartTime, "Already started."); require(block.timestamp < _time, "Time input is too early."); uint256 length = poolInfo.length; uint256 pid = 0; uint256 _lastRewardTime; for (pid = 0; pid < length; pid += 1) { PoolInfo storage pool = poolInfo[pid]; _lastRewardTime = pool.lastRewardTime; if (_lastRewardTime == poolStartTime || _lastRewardTime < _time) { pool.lastRewardTime = _time; } } poolStartTime = _time; } function setPoolEndTime( uint256 _time ) public onlyAuthorized { require(block.timestamp < poolStartTime, "Already started."); require(poolStartTime < _time, "Time input is too early."); poolEndTime = _time; runningTime = poolEndTime - poolStartTime; } function checkPoolDuplicate(IERC20 _token) internal view { uint256 length = poolInfo.length; uint256 pid; for (pid = 0; pid < length; pid += 1) { require(poolInfo[pid].token != _token, "GameGenesisRewardPool: existing pool?"); } } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, uint256 _lastRewardTime ) public onlyOperator { checkPoolDuplicate(_token); if (_withUpdate) { massUpdatePools(); } if (block.timestamp < poolStartTime) { // chef is sleeping if (_lastRewardTime < poolStartTime) { _lastRewardTime = poolStartTime; } } else { // chef is cooking if (_lastRewardTime < block.timestamp) { _lastRewardTime = block.timestamp; } } bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp); poolInfo.push(PoolInfo({ token : _token, allocPoint : _allocPoint, lastRewardTime : _lastRewardTime, accGamePerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's GAME allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } function setDepositFee(uint256 _depositFee) public onlyOperator { require(_depositFee <= 100, "Deposit fee must be less than 1%"); depositFee = _depositFee; } function getGamePerSecondInPool(uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 _poolGamePerSecond = gamePerSecond.mul(pool.allocPoint).div(totalAllocPoint); return _poolGamePerSecond; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) { if (_fromTime >= _toTime) return 0; if (_toTime >= poolEndTime) { if (_fromTime >= poolEndTime) return 0; if (_fromTime <= poolStartTime) return poolEndTime.sub(poolStartTime).mul(gamePerSecond); return poolEndTime.sub(_fromTime).mul(gamePerSecond); } else { if (_toTime <= poolStartTime) return 0; if (_fromTime <= poolStartTime) return _toTime.sub(poolStartTime).mul(gamePerSecond); return _toTime.sub(_fromTime).mul(gamePerSecond); } } // View function to see pending GAME on frontend. function pendingGAME(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGamePerShare = pool.accGamePerShare; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp); uint256 _gameReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accGamePerShare = accGamePerShare.add(_gameReward.mul(1e18).div(tokenSupply)); } return user.amount.mul(accGamePerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() internal { // Too scared of scary reentrancy warnings. Internal version. uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables for all pools. Be careful of gas spending! function forceMassUpdatePools() external onlyAuthorized { // Too scared of scary reentrancy warnings. External version. massUpdatePools(); } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal { // Too scared of scary reentrancy warnings. Internal version. PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTime) { return; } uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { pool.lastRewardTime = block.timestamp; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); // Reentrancy issue? But this can't be used maliciously... Can it? A malicious token is what we should be more worried about. } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp); uint256 _gameReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accGamePerShare = pool.accGamePerShare.add(_gameReward.mul(1e18).div(tokenSupply)); } pool.lastRewardTime = block.timestamp; } // Update reward variables of the given pool to be up-to-date. function forceUpdatePool(uint256 _pid) external onlyAuthorized { // Too scared of scary reentrancy warnings. External version. updatePool(_pid); } // Deposit LP tokens. function deposit(uint256 _pid, uint256 _amount) public onlyOneBlock { // Poor smart contracts, can't deposit to multiple pools at once... But my OCD will not allow this. address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accGamePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeGameTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { uint256 feeAmount = _amount.mul(depositFee).div(10000); uint256 amountToDeposit = _amount.sub(feeAmount); if(feeAmount > 0) pool.token.safeTransferFrom(_sender, treasury.daoFund(), feeAmount); pool.token.safeTransferFrom(_sender, address(this), amountToDeposit); user.amount = user.amount.add(amountToDeposit); } user.rewardDebt = user.amount.mul(pool.accGamePerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens. // No withdrawal fees or locks for Genesis Pools. function withdraw(uint256 _pid, uint256 _amount) public onlyOneBlock { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accGamePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeGameTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accGamePerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public onlyOneBlock { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.token.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe GAME transfer function, just in case if rounding error causes pool to not have enough GAMEs. function safeGameTransfer(address _to, uint256 _amount) internal { uint256 _gameBalance = game.balanceOf(address(this)); if (_gameBalance > 0) { if (_amount > _gameBalance) { game.safeTransfer(_to, _gameBalance); } else { game.safeTransfer(_to, _amount); } } } function getRequiredAllocation() public view returns (uint256) { uint256 _generatedReward = getGeneratedReward(poolStartTime, poolEndTime); return _generatedReward; } function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { if (block.timestamp < poolEndTime + 90 days) { // do not allow to drain core token (GAME or lps) if less than 90 days after pool ends require(_token != game, "game"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.token, "pool.token"); } } _token.safeTransfer(to, amount); } }
do not allow to drain core token (GAME or lps) if less than 90 days after pool ends
function getRequiredAllocation() public view returns (uint256) } if (block.timestamp < poolEndTime + 90 days) { require(_token != game, "game"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.token, "pool.token"); } } _token.safeTransfer(to, amount);
5,537,228
[ 1, 2896, 486, 1699, 358, 15427, 2922, 1147, 261, 43, 1642, 578, 328, 1121, 13, 309, 5242, 2353, 8566, 4681, 1839, 2845, 3930, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 19881, 17353, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 203, 565, 289, 203, 203, 3639, 309, 261, 2629, 18, 5508, 411, 2845, 25255, 397, 8566, 4681, 13, 288, 203, 5411, 2583, 24899, 2316, 480, 7920, 16, 315, 13957, 8863, 203, 5411, 2254, 5034, 769, 273, 2845, 966, 18, 2469, 31, 203, 5411, 364, 261, 11890, 5034, 4231, 273, 374, 31, 4231, 411, 769, 31, 965, 6610, 13, 288, 203, 7734, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 6610, 15533, 203, 7734, 2583, 24899, 2316, 480, 2845, 18, 2316, 16, 315, 6011, 18, 2316, 8863, 203, 5411, 289, 203, 3639, 289, 203, 3639, 389, 2316, 18, 4626, 5912, 12, 869, 16, 3844, 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 ]
/** * Copyright 2017–2018, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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); } /** * @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 DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * 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, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract UnlimitedAllowanceToken is StandardToken { uint internal constant MAX_UINT = 2**256 - 1; /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance, and to add revert reasons. /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transferFrom( address _from, address _to, uint256 _value) public returns (bool) { uint allowance = allowed[_from][msg.sender]; require(_value <= balances[_from], "insufficient balance"); require(_value <= allowance, "insufficient allowance"); require(_to != address(0), "token burn not allowed"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if (allowance < MAX_UINT) { allowed[_from][msg.sender] = allowance.sub(_value); } emit Transfer(_from, _to, _value); return true; } /// @dev Transfer token for a specified address, modified to add revert reasons. /// @param _to The address to transfer to. /// @param _value The amount to be transferred. function transfer( address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "insufficient balance"); require(_to != address(0), "token burn not allowed"); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } } contract BZRxToken is UnlimitedAllowanceToken, DetailedERC20, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); event LockingFinished(); bool public mintingFinished = false; bool public lockingFinished = false; mapping (address => bool) public minters; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(minters[msg.sender]); _; } modifier isLocked() { require(!lockingFinished); _; } constructor() public DetailedERC20( "BZRX Protocol Token", "BZRX", 18 ) { minters[msg.sender] = true; } /// @dev ERC20 transferFrom function /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transferFrom( address _from, address _to, uint256 _value) public returns (bool) { if (lockingFinished || minters[msg.sender]) { return super.transferFrom( _from, _to, _value ); } revert("this token is locked for transfers"); } /// @dev ERC20 transfer function /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function transfer( address _to, uint256 _value) public returns (bool) { if (lockingFinished || minters[msg.sender]) { return super.transfer( _to, _value ); } revert("this token is locked for transfers"); } /// @dev Allows minter to initiate a transfer on behalf of another spender /// @param _spender Minter with permission to spend. /// @param _from Address to transfer from. /// @param _to Address to transfer to. /// @param _value Amount to transfer. /// @return Success of transfer. function minterTransferFrom( address _spender, address _from, address _to, uint256 _value) public hasMintPermission canMint returns (bool) { require(canTransfer( _spender, _from, _value), "canTransfer is false"); require(_to != address(0), "token burn not allowed"); uint allowance = allowed[_from][_spender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if (allowance < MAX_UINT) { allowed[_from][_spender] = allowance.sub(_value); } emit Transfer(_from, _to, _value); return true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_to != address(0), "token burn not allowed"); 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() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * @dev Function to stop locking token. * @return True if the operation was successful. */ function finishLocking() public onlyOwner isLocked returns (bool) { lockingFinished = true; emit LockingFinished(); return true; } /** * @dev Function to add minter address. * @return True if the operation was successful. */ function addMinter( address _minter) public onlyOwner canMint returns (bool) { minters[_minter] = true; return true; } /** * @dev Function to remove minter address. * @return True if the operation was successful. */ function removeMinter( address _minter) public onlyOwner canMint returns (bool) { minters[_minter] = false; return true; } /** * @dev Function to check balance and allowance for a spender. * @return True transfer will succeed based on balance and allowance. */ function canTransfer( address _spender, address _from, uint256 _value) public view returns (bool) { return ( balances[_from] >= _value && (_spender == _from || allowed[_from][_spender] >= _value) ); } } interface WETHInterface { function deposit() external payable; function withdraw(uint wad) external; } interface PriceFeed { function read() external view returns (bytes32); } contract BZRxTokenSale is Ownable { using SafeMath for uint256; struct TokenPurchases { uint totalETH; uint totalTokens; uint totalTokenBonus; } event BonusChanged(uint oldBonus, uint newBonus); event TokenPurchase(address indexed buyer, uint ethAmount, uint ethRate, uint tokensReceived); event SaleOpened(uint bonusMultiplier); event SaleClosed(uint bonusMultiplier); bool public saleClosed = true; address public bZRxTokenContractAddress; // BZRX Token address public bZxVaultAddress; // bZx Vault address public wethContractAddress; // WETH Token address public priceContractAddress; // MakerDao Medianizer price feed // The current token bonus offered to purchasers (example: 110 == 10% bonus) uint public bonusMultiplier; uint public ethRaised; address[] public purchasers; mapping (address => TokenPurchases) public purchases; bool public whitelistEnforced = false; mapping (address => uint) public whitelist; modifier saleOpen() { require(!saleClosed, "sale is closed"); _; } modifier whitelisted(address user, uint value) { require(canPurchaseAmount(user, value), "not whitelisted"); _; } constructor( address _bZRxTokenContractAddress, address _bZxVaultAddress, address _wethContractAddress, address _priceContractAddress, uint _bonusMultiplier) public { require(_bonusMultiplier > 100); bZRxTokenContractAddress = _bZRxTokenContractAddress; bZxVaultAddress = _bZxVaultAddress; wethContractAddress = _wethContractAddress; priceContractAddress = _priceContractAddress; bonusMultiplier = _bonusMultiplier; } function() public payable { buyToken(); } function buyToken() public payable saleOpen whitelisted(msg.sender, msg.value) returns (bool) { require(msg.value > 0, "no ether sent"); uint ethRate = getEthRate(); ethRaised += msg.value; uint tokenAmount = msg.value // amount of ETH sent .mul(ethRate).div(10**18) // curent ETH/USD rate .mul(1000).div(73); // fixed price per token $0.073 uint tokenAmountAndBonus = tokenAmount .mul(bonusMultiplier).div(100); TokenPurchases storage purchase = purchases[msg.sender]; if (purchase.totalETH == 0) { purchasers.push(msg.sender); } purchase.totalETH += msg.value; purchase.totalTokens += tokenAmountAndBonus; purchase.totalTokenBonus += tokenAmountAndBonus.sub(tokenAmount); emit TokenPurchase(msg.sender, msg.value, ethRate, tokenAmountAndBonus); return BZRxToken(bZRxTokenContractAddress).mint( msg.sender, tokenAmountAndBonus ); } // conforms to ERC20 transferFrom function for BZRX token support function transferFrom( address _from, address _to, uint256 _value) public saleOpen returns (bool) { require(msg.sender == bZxVaultAddress, "only the bZx vault can call this function"); if (BZRxToken(bZRxTokenContractAddress).canTransfer(msg.sender, _from, _value)) { return BZRxToken(bZRxTokenContractAddress).minterTransferFrom( msg.sender, _from, _to, _value ); } else { uint ethRate = getEthRate(); uint wethValue = _value // amount of BZRX .mul(73).div(1000) // fixed price per token $0.073 .mul(10**18).div(ethRate); // curent ETH/USD rate // discount on purchase wethValue -= wethValue.mul(bonusMultiplier).div(100).sub(wethValue); require(canPurchaseAmount(_from, wethValue), "not whitelisted"); require(StandardToken(wethContractAddress).transferFrom( _from, this, wethValue ), "weth transfer failed"); ethRaised += wethValue; TokenPurchases storage purchase = purchases[_from]; if (purchase.totalETH == 0) { purchasers.push(_from); } purchase.totalETH += wethValue; purchase.totalTokens += _value; return BZRxToken(bZRxTokenContractAddress).mint( _to, _value ); } } function closeSale( bool _closed) public onlyOwner returns (bool) { saleClosed = _closed; if (_closed) emit SaleClosed(bonusMultiplier); else emit SaleOpened(bonusMultiplier); return true; } function changeBZRxTokenContract( address _bZRxTokenContractAddress) public onlyOwner returns (bool) { bZRxTokenContractAddress = _bZRxTokenContractAddress; return true; } function changeBZxVault( address _bZxVaultAddress) public onlyOwner returns (bool) { bZxVaultAddress = _bZxVaultAddress; return true; } function changeWethContract( address _wethContractAddress) public onlyOwner returns (bool) { wethContractAddress = _wethContractAddress; return true; } function changePriceContract( address _priceContractAddress) public onlyOwner returns (bool) { priceContractAddress = _priceContractAddress; return true; } function changeBonusMultiplier( uint _newBonusMultiplier) public onlyOwner returns (bool) { require(bonusMultiplier != _newBonusMultiplier && _newBonusMultiplier > 100); emit BonusChanged(bonusMultiplier, _newBonusMultiplier); bonusMultiplier = _newBonusMultiplier; return true; } function unwrapEth() public onlyOwner returns (bool) { uint balance = StandardToken(wethContractAddress).balanceOf.gas(4999)(this); if (balance == 0) return false; WETHInterface(wethContractAddress).withdraw(balance); return true; } function transferEther( address _to, uint _value) public onlyOwner returns (bool) { uint amount = _value; if (amount > address(this).balance) { amount = address(this).balance; } return (_to.send(amount)); } function enforceWhitelist( bool _isEnforced) public onlyOwner returns (bool) { whitelistEnforced = _isEnforced; return true; } function setWhitelist( address[] _users, uint[] _values) public onlyOwner returns (bool) { require(_users.length == _values.length, "users and values count mismatch"); for (uint i=0; i < _users.length; i++) { whitelist[_users[i]] = _values[i]; } return true; } function getEthRate() public view returns (uint) { return uint(PriceFeed(priceContractAddress).read()); } function canPurchaseAmount( address _user, uint _value) public view returns (bool) { if (!whitelistEnforced || (whitelist[_user] > 0 && purchases[_user].totalETH.add(_value) <= whitelist[_user])) { return true; } else { return false; } } }
conforms to ERC20 transferFrom function for BZRX token support discount on purchase
function transferFrom( address _from, address _to, uint256 _value) public saleOpen returns (bool) { require(msg.sender == bZxVaultAddress, "only the bZx vault can call this function"); if (BZRxToken(bZRxTokenContractAddress).canTransfer(msg.sender, _from, _value)) { return BZRxToken(bZRxTokenContractAddress).minterTransferFrom( msg.sender, _from, _to, _value ); uint ethRate = getEthRate(); wethValue -= wethValue.mul(bonusMultiplier).div(100).sub(wethValue); require(canPurchaseAmount(_from, wethValue), "not whitelisted"); require(StandardToken(wethContractAddress).transferFrom( _from, this, wethValue ), "weth transfer failed"); ethRaised += wethValue; TokenPurchases storage purchase = purchases[_from]; if (purchase.totalETH == 0) { purchasers.push(_from); } purchase.totalETH += wethValue; purchase.totalTokens += _value; return BZRxToken(bZRxTokenContractAddress).mint( _to, _value ); } }
14,630,016
[ 1, 591, 9741, 358, 4232, 39, 3462, 7412, 1265, 445, 364, 605, 62, 54, 60, 1147, 2865, 12137, 603, 23701, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 1132, 13, 203, 3639, 1071, 203, 3639, 272, 5349, 3678, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 324, 62, 92, 12003, 1887, 16, 315, 3700, 326, 324, 62, 92, 9229, 848, 745, 333, 445, 8863, 203, 540, 203, 3639, 309, 261, 38, 62, 27741, 1345, 12, 70, 62, 27741, 1345, 8924, 1887, 2934, 4169, 5912, 12, 3576, 18, 15330, 16, 389, 2080, 16, 389, 1132, 3719, 288, 203, 5411, 327, 605, 62, 27741, 1345, 12, 70, 62, 27741, 1345, 8924, 1887, 2934, 1154, 387, 5912, 1265, 12, 203, 7734, 1234, 18, 15330, 16, 203, 7734, 389, 2080, 16, 203, 7734, 389, 869, 16, 203, 7734, 389, 1132, 203, 5411, 11272, 203, 5411, 2254, 13750, 4727, 273, 4774, 451, 4727, 5621, 203, 2398, 203, 203, 5411, 341, 546, 620, 3947, 341, 546, 620, 18, 16411, 12, 18688, 407, 23365, 2934, 2892, 12, 6625, 2934, 1717, 12, 91, 546, 620, 1769, 203, 203, 5411, 2583, 12, 4169, 23164, 6275, 24899, 2080, 16, 341, 546, 620, 3631, 315, 902, 26944, 8863, 203, 203, 5411, 2583, 12, 8336, 1345, 12, 91, 546, 8924, 1887, 2934, 13866, 1265, 12, 203, 7734, 389, 2080, 16, 203, 7734, 333, 16, 203, 7734, 341, 546, 620, 203, 5411, 262, 16, 315, 91, 546, 7412, 2535, 8863, 203, 203, 5411, 13750, 12649, 5918, 1011, 341, 546, 620, 31, 203, 203, 5411, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-06-17 */ // SPDX-License-Identifier: MIT // File 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File 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() { 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 contracts/IBEP20.sol pragma solidity ^0.8.0; /** * @dev Interface of the BEP20 standard as defined in the EIP. */ interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/extensions/IBEP20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the BEP20 standard. * * _Available since v4.1._ */ interface IBEP20Metadata is IBEP20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File contracts/security/Pausable.sol 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 Ownable { /** * @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()); } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { _paused = true; emit Paused(msg.sender); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { _paused = false; emit Unpaused(msg.sender); return true; } } // File contracts/BEP20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IBEP20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of BEP20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IBEP20-approve}. */ contract BEP20 is Context, IBEP20, IBEP20Metadata, Pausable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {BEP20} 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 * {IBEP20-balanceOf} and {IBEP20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IBEP20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IBEP20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IBEP20-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 whenNotPaused returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IBEP20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IBEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override whenNotPaused returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IBEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override whenNotPaused returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "BEP20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IBEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual whenNotPaused returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IBEP20-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 whenNotPaused returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "BEP20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "BEP20: 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), "BEP20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "BEP20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "BEP20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File contracts/LGEWhitelisted.sol pragma solidity ^0.8.0; contract LGEWhitelisted is Context { struct WhitelistRound { uint256 duration; uint256 amountMax; mapping(address => bool) addresses; mapping(address => uint256) purchased; } WhitelistRound[] public _lgeWhitelistRounds; uint256 public _lgeTimestamp; address public _lgePairAddress; address public _whitelister; event WhitelisterTransferred(address indexed previousWhitelister, address indexed newWhitelister); constructor() { _whitelister = _msgSender(); } modifier onlyWhitelister() { require(_whitelister == _msgSender(), "Caller is not the whitelister"); _; } function renounceWhitelister() external onlyWhitelister { emit WhitelisterTransferred(_whitelister, address(0)); _whitelister = address(0); } function transferWhitelister(address newWhitelister) external onlyWhitelister { _transferWhitelister(newWhitelister); } function _transferWhitelister(address newWhitelister) internal { require(newWhitelister != address(0), "New whitelister is the zero address"); emit WhitelisterTransferred(_whitelister, newWhitelister); _whitelister = newWhitelister; } /* * createLGEWhitelist - Call this after initial Token Generation Event (TGE) * * pairAddress - address generated from createPair() event on DEX * durations - array of durations (seconds) for each whitelist rounds * amountsMax - array of max amounts (TOKEN decimals) for each whitelist round * */ function createLGEWhitelist( address pairAddress, uint256[] calldata durations, uint256[] calldata amountsMax ) external onlyWhitelister() { require(durations.length == amountsMax.length, "Invalid whitelist(s)"); _lgePairAddress = pairAddress; if (durations.length > 0) { delete _lgeWhitelistRounds; for (uint256 i = 0; i < durations.length; i++) { WhitelistRound storage whitelistRound = _lgeWhitelistRounds.push(); whitelistRound.duration = durations[i]; whitelistRound.amountMax = amountsMax[i]; } } } /* * modifyLGEWhitelistAddresses - Define what addresses are included/excluded from a whitelist round * * index - 0-based index of round to modify whitelist * duration - period in seconds from LGE event or previous whitelist round * amountMax - max amount (TOKEN decimals) for each whitelist round * */ function modifyLGEWhitelist( uint256 index, uint256 duration, uint256 amountMax, address[] calldata addresses, bool enabled ) external onlyWhitelister() { require(index < _lgeWhitelistRounds.length, "Invalid index"); require(amountMax > 0, "Invalid amountMax"); if (duration != _lgeWhitelistRounds[index].duration) _lgeWhitelistRounds[index].duration = duration; if (amountMax != _lgeWhitelistRounds[index].amountMax) _lgeWhitelistRounds[index].amountMax = amountMax; for (uint256 i = 0; i < addresses.length; i++) { _lgeWhitelistRounds[index].addresses[addresses[i]] = enabled; } } /* * getLGEWhitelistRound * * returns: * * 1. whitelist round number ( 0 = no active round now ) * 2. duration, in seconds, current whitelist round is active for * 3. timestamp current whitelist round closes at * 4. maximum amount a whitelister can purchase in this round * 5. is caller whitelisted * 6. how much caller has purchased in current whitelist round * */ function getLGEWhitelistRound() public view returns ( uint256, uint256, uint256, uint256, bool, uint256 ) { if (_lgeTimestamp > 0) { uint256 wlCloseTimestampLast = _lgeTimestamp; for (uint256 i = 0; i < _lgeWhitelistRounds.length; i++) { WhitelistRound storage wlRound = _lgeWhitelistRounds[i]; wlCloseTimestampLast = wlCloseTimestampLast + wlRound.duration; if (block.timestamp <= wlCloseTimestampLast) return ( i + 1, wlRound.duration, wlCloseTimestampLast, wlRound.amountMax, wlRound.addresses[_msgSender()], wlRound.purchased[_msgSender()] ); } } return (0, 0, 0, 0, false, 0); } /* * _applyLGEWhitelist - internal function to be called initially before any transfers * */ function _applyLGEWhitelist( address sender, address recipient, uint256 amount ) internal { if (_lgePairAddress == address(0) || _lgeWhitelistRounds.length == 0) return; if (_lgeTimestamp == 0 && sender != _lgePairAddress && recipient == _lgePairAddress && amount > 0) _lgeTimestamp = block.timestamp; if (sender == _lgePairAddress && recipient != _lgePairAddress) { //buying (uint256 wlRoundNumber, , , , , ) = getLGEWhitelistRound(); if (wlRoundNumber > 0) { WhitelistRound storage wlRound = _lgeWhitelistRounds[wlRoundNumber - 1]; require(wlRound.addresses[recipient], "LGE - Buyer is not whitelisted"); uint256 amountRemaining = 0; if (wlRound.purchased[recipient] < wlRound.amountMax) amountRemaining = wlRound.amountMax - wlRound.purchased[recipient]; require(amount <= amountRemaining, "LGE - Amount exceeds whitelist maximum"); wlRound.purchased[recipient] = wlRound.purchased[recipient] + amount; } } } } // File contracts/Roseon.sol pragma solidity ^0.8.0; contract LockCoin is BEP20 { constructor( string memory name, string memory symbol, uint256 totalSupply ) BEP20(name, symbol) { _mint(_msgSender(), totalSupply); _locker = _msgSender(); } event Unlock(address indexed addressLock, uint256 amount); event AddAddressLock(address indexed addressLock, uint256 amount); event LockerTransferred(address indexed previousLocker, address indexed newLocker); address public _locker; struct ScheduleLock { uint256 unlockTime; uint256 amount; } struct TimeLockByAddress { uint256 nextIndexTimeLock; uint256 totalLock; ScheduleLock[] arrTimeLock; } mapping(address => TimeLockByAddress) mappingAddressToLock; modifier onlyLocker() { require(_locker == _msgSender(), "Caller is not the locker"); _; } function renounceLocker() external onlyLocker { emit LockerTransferred(_locker, address(0)); _locker = address(0); } function transferLocker(address newLocker) external onlyLocker { _transferLocker(newLocker); } function _transferLocker(address newLocker) internal { require(newLocker != address(0), "New locker is the zero address"); emit LockerTransferred(_locker, newLocker); _locker = newLocker; } function _addScheduleLockByAddress( address _addressLock, uint256 _unlockTime, uint256 _amount ) internal { mappingAddressToLock[_addressLock].arrTimeLock.push(ScheduleLock(_unlockTime, _amount)); } function _updateTotalLockByAddress( address _addressLock, uint256 _totalLock, uint256 _nextIndexLock ) internal { mappingAddressToLock[_addressLock].nextIndexTimeLock = _nextIndexLock; mappingAddressToLock[_addressLock].totalLock = _totalLock; emit AddAddressLock(_addressLock, _totalLock); } /** * @dev Unlock token of "_addressLock" with timeline lock */ function _unLock(address _addressLock) internal { if (mappingAddressToLock[_addressLock].totalLock == 0) { return; } TimeLockByAddress memory timeLockByAddress = mappingAddressToLock[_addressLock]; uint256 totalUnlock = 0; while ( timeLockByAddress.nextIndexTimeLock < timeLockByAddress.arrTimeLock.length && block.timestamp >= timeLockByAddress.arrTimeLock[timeLockByAddress.nextIndexTimeLock].unlockTime ) { emit Unlock(_addressLock, timeLockByAddress.arrTimeLock[timeLockByAddress.nextIndexTimeLock].amount); totalUnlock += timeLockByAddress.arrTimeLock[timeLockByAddress.nextIndexTimeLock].amount; timeLockByAddress.nextIndexTimeLock += 1; } if (totalUnlock > 0) { _updateTotalLockByAddress( _addressLock, timeLockByAddress.totalLock - totalUnlock, timeLockByAddress.nextIndexTimeLock ); } } /** * @dev get total amount lock of address */ function getLockedAmount(address _addressLock) public view returns (uint256 amount) { return mappingAddressToLock[_addressLock].totalLock; } /** * @dev get next shedule unlock time of address lock */ function getNextScheduleUnlock(address _addressLock) public view returns ( uint256 index, uint256 unlockTime, uint256 amount ) { TimeLockByAddress memory timeLockByAddress = mappingAddressToLock[_addressLock]; return ( timeLockByAddress.nextIndexTimeLock, timeLockByAddress.arrTimeLock[timeLockByAddress.nextIndexTimeLock].unlockTime, timeLockByAddress.arrTimeLock[timeLockByAddress.nextIndexTimeLock].amount ); } /** * @dev update array schedule lock token of address */ function overwriteScheduleLock( address _addressLock, uint256[] memory _arrAmount, uint256[] memory _arrUnlockTime ) public onlyLocker { require(_arrAmount.length > 0 && _arrAmount.length == _arrUnlockTime.length, "The parameter passed was wrong"); require(mappingAddressToLock[_addressLock].totalLock > 0, "Address must in list lock"); _overwriteTimeLockByAddress(_addressLock, _arrAmount, _arrUnlockTime); } /** * @dev get lock time and amount lock by address at a time */ function getScheduleLock(address _addressLock, uint256 _index) public view returns (uint256, uint256) { return ( mappingAddressToLock[_addressLock].arrTimeLock[_index].amount, mappingAddressToLock[_addressLock].arrTimeLock[_index].unlockTime ); } /** * @dev add list timeline lock and total amount lock by address */ function addScheduleLockByAddress( address _addressLock, uint256[] memory _arrAmount, uint256[] memory _arrUnlockTime ) public onlyLocker { require(_arrAmount.length > 0 && _arrAmount.length == _arrUnlockTime.length, "The parameter passed was wrong"); require(mappingAddressToLock[_addressLock].totalLock == 0, "Address must not in list lock"); _overwriteTimeLockByAddress(_addressLock, _arrAmount, _arrUnlockTime); } function unlockRoseon() public whenNotPaused { _unLock(_msgSender()); } /** * @dev function overwrite schedule time lock and total by address lock */ function _overwriteTimeLockByAddress( address _addressLock, uint256[] memory _arrAmount, uint256[] memory _arrUnlockTime ) internal returns (uint256) { uint256 totalLock = 0; delete mappingAddressToLock[_addressLock].arrTimeLock; for (uint256 i = 0; i < _arrAmount.length; i++) { require(_arrUnlockTime[i] > 0, "The timeline must be greater than 0"); if (i != _arrAmount.length - 1) { require( _arrUnlockTime[i + 1] > _arrUnlockTime[i], "The next timeline must be greater than the previous" ); } _addScheduleLockByAddress(_addressLock, _arrUnlockTime[i], _arrAmount[i]); totalLock += _arrAmount[i]; } _updateTotalLockByAddress(_addressLock, totalLock, 0); return totalLock; } } contract RoseonToken is LockCoin, LGEWhitelisted { constructor() LockCoin("Roseon token", "ROSN", 100000000 * 10**18) {} function transfer(address _receiver, uint256 _amount) public override returns (bool success) { _unLock(_msgSender()); require(_amount <= getAvailableBalance(_msgSender()), "Balance is insufficient"); return BEP20.transfer(_receiver, _amount); } function transferFrom( address _from, address _receiver, uint256 _amount ) public override returns (bool) { _unLock(_from); require(_amount <= getAvailableBalance(_from), "Balance is insufficient"); return BEP20.transferFrom(_from, _receiver, _amount); } function getAvailableBalance(address _lockedAddress) public view returns (uint256 amount) { uint256 balance = balanceOf(_lockedAddress); uint256 lockedAmount = getLockedAmount(_lockedAddress); if (balance <= lockedAmount) return 0; return balance - lockedAmount; } function _beforeTokenTransfer( address _from, address _to, uint256 _amount ) internal override { super._beforeTokenTransfer(_from, _to, _amount); _applyLGEWhitelist(_from, _to, _amount); } }
* @dev get next shedule unlock time of address lock/
function getNextScheduleUnlock(address _addressLock) public view returns ( uint256 index, uint256 unlockTime, uint256 amount ) { TimeLockByAddress memory timeLockByAddress = mappingAddressToLock[_addressLock]; return ( timeLockByAddress.nextIndexTimeLock, timeLockByAddress.arrTimeLock[timeLockByAddress.nextIndexTimeLock].unlockTime, timeLockByAddress.arrTimeLock[timeLockByAddress.nextIndexTimeLock].amount ); }
2,296,416
[ 1, 588, 1024, 699, 329, 725, 7186, 813, 434, 1758, 2176, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6927, 6061, 7087, 12, 2867, 389, 2867, 2531, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 770, 16, 203, 5411, 2254, 5034, 7186, 950, 16, 203, 5411, 2254, 5034, 3844, 203, 3639, 262, 203, 565, 288, 203, 3639, 2647, 2531, 858, 1887, 3778, 813, 2531, 858, 1887, 273, 2874, 1887, 774, 2531, 63, 67, 2867, 2531, 15533, 203, 3639, 327, 261, 203, 5411, 813, 2531, 858, 1887, 18, 4285, 1016, 950, 2531, 16, 203, 5411, 813, 2531, 858, 1887, 18, 5399, 950, 2531, 63, 957, 2531, 858, 1887, 18, 4285, 1016, 950, 2531, 8009, 26226, 950, 16, 203, 5411, 813, 2531, 858, 1887, 18, 5399, 950, 2531, 63, 957, 2531, 858, 1887, 18, 4285, 1016, 950, 2531, 8009, 8949, 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, -100 ]
./full_match/77/0xB1274c8c44B5066d6777dfBB28f4B38bAd900F48/sources/contracts/3_Ballot.sol
pragma solidity >=0.7.0 <0.9.0;pragma experimental ABIEncoderV2;* @title Ballot @dev Implements voting process along with vote delegation/
contract Ballot { struct Voter { } struct Proposal { Voter [] voters; } function test(Voter[] memory _voters) public pure returns(Voter[] memory) { return _voters; } function test_1(Proposal[] memory _voters) public pure returns(Proposal[] memory) { return _voters; } function test_2(bool f) public pure returns(bool){ return f; } function test_3(uint[] memory ints, bool f) public pure returns(uint[] memory, bool){ return (ints, f); } function test_4(uint[] memory ints, Voter[] memory voters, bool f) public pure returns(uint[] memory, bool, Voter[] memory){ return (ints, f, voters); } }
5,047,766
[ 1, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 29, 18, 20, 31, 683, 9454, 23070, 10336, 45, 7204, 58, 22, 31, 225, 605, 454, 352, 225, 29704, 331, 17128, 1207, 7563, 598, 12501, 23595, 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, 16351, 605, 454, 352, 288, 203, 27699, 203, 565, 1958, 776, 20005, 288, 203, 565, 289, 203, 203, 565, 1958, 19945, 288, 203, 3639, 776, 20005, 5378, 331, 352, 414, 31, 203, 565, 289, 203, 377, 203, 565, 445, 1842, 12, 58, 20005, 8526, 3778, 389, 90, 352, 414, 13, 1071, 16618, 1135, 12, 58, 20005, 8526, 3778, 13, 288, 203, 3639, 327, 389, 90, 352, 414, 31, 203, 565, 289, 203, 203, 565, 445, 1842, 67, 21, 12, 14592, 8526, 3778, 389, 90, 352, 414, 13, 1071, 16618, 1135, 12, 14592, 8526, 3778, 13, 288, 203, 3639, 327, 389, 90, 352, 414, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 1842, 67, 22, 12, 6430, 284, 13, 1071, 16618, 1135, 12, 6430, 15329, 203, 3639, 327, 284, 31, 203, 565, 289, 203, 21281, 377, 203, 565, 445, 1842, 67, 23, 12, 11890, 8526, 3778, 15542, 16, 1426, 284, 13, 1071, 16618, 1135, 12, 11890, 8526, 3778, 16, 1426, 15329, 203, 3639, 327, 261, 28142, 16, 284, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 1842, 67, 24, 12, 11890, 8526, 3778, 15542, 16, 776, 20005, 8526, 3778, 331, 352, 414, 16, 1426, 284, 13, 1071, 16618, 1135, 12, 11890, 8526, 3778, 16, 1426, 16, 776, 20005, 8526, 3778, 15329, 203, 3639, 327, 261, 28142, 16, 284, 16, 331, 352, 414, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x511C86d94BD667aba09e5Ee5B0d8Da157Df5f4bf/sources/$ORANGEPEPE.sol
* @dev Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance<amount?0:fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
15,981,031
[ 1, 19297, 1375, 8949, 68, 434, 2430, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 1220, 2713, 445, 353, 7680, 358, 288, 13866, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 5859, 1147, 1656, 281, 16, 9026, 310, 1791, 28757, 16, 5527, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2080, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 19, 10752, 2426, 486, 3323, 30, 326, 2142, 434, 777, 324, 26488, 353, 3523, 1845, 635, 2078, 3088, 1283, 16, 471, 326, 2142, 353, 21096, 635, 15267, 310, 1508, 5504, 310, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 3639, 2254, 5034, 628, 13937, 273, 389, 70, 26488, 63, 2080, 15533, 203, 3639, 2583, 12, 2080, 13937, 1545, 3844, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 11013, 8863, 203, 565, 22893, 288, 203, 3639, 389, 70, 26488, 63, 2080, 65, 273, 628, 13937, 32, 8949, 35, 20, 30, 2080, 13937, 300, 3844, 31, 203, 3639, 389, 70, 26488, 63, 869, 65, 1011, 3844, 31, 203, 565, 289, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 3639, 389, 5205, 1345, 5912, 12, 2080, 16, 358, 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 ]
./full_match/43113/0x2Ad8a117CAA5574f34CF28312E5715c153a3a147/sources/contracts/SmartAlpha.sol
@notice Return the total amount of underlying in the queues @return amount of underlying in the queues
function underlyingInQueues() public view returns (uint256) { return queuedJuniorsUnderlyingIn + queuedSeniorsUnderlyingIn + queuedJuniorsUnderlyingOut + queuedSeniorsUnderlyingOut; }
7,165,496
[ 1, 990, 326, 2078, 3844, 434, 6808, 316, 326, 11897, 327, 3844, 434, 6808, 316, 326, 11897, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6808, 382, 17428, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 12234, 46, 318, 77, 1383, 14655, 6291, 382, 397, 12234, 55, 275, 77, 1383, 14655, 6291, 382, 397, 12234, 46, 318, 77, 1383, 14655, 6291, 1182, 397, 12234, 55, 275, 77, 1383, 14655, 6291, 1182, 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 ]
./partial_match/1/0xFBBa6F338D9b8a84C7b2c521735d7204710Ab17f/sources/RefundVault.sol
* @dev Transfer tokens from one address to another @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered/ Check is not needed because sub(_allowance, _value) will already throw if this condition is not met require (_value <= _allowance);
function transferFrom(address _from, address _to, uint256 _value) returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; }
15,649,263
[ 1, 5912, 2430, 628, 1245, 1758, 358, 4042, 225, 389, 2080, 1758, 1021, 1758, 1492, 1846, 2545, 358, 1366, 2430, 628, 225, 389, 869, 1758, 1021, 1758, 1492, 1846, 2545, 358, 7412, 358, 225, 389, 1132, 2254, 5034, 326, 2125, 659, 434, 2430, 358, 506, 7412, 329, 19, 2073, 353, 486, 3577, 2724, 720, 24899, 5965, 1359, 16, 389, 1132, 13, 903, 1818, 604, 309, 333, 2269, 353, 486, 5100, 2583, 261, 67, 1132, 1648, 389, 5965, 1359, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1135, 261, 6430, 13, 288, 203, 565, 2254, 5034, 389, 5965, 1359, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 15533, 203, 203, 203, 565, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 389, 5965, 1359, 18, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.1; import "../../openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; import "../../openzeppelin-contracts/contracts/token/ERC721/IERC721.sol"; import "../../openzeppelin-contracts/contracts/token/ERC1155/IERC1155.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 {setOwner}. * * This module is used through inheritance. It will make available the modifiers * `onlyOwner`/`onlyOperator`, which can be applied to your functions to * restrict their use to the owner. * * Operator account can be set to MultiSig contract. * * In case someone mistakenly sent other tokens to the contract, or ETH, * there are functions to transfer those funds to a different address. */ contract AccessControl { mapping (address=>bool) ownerAddress; mapping (address=>bool) operatorAddress; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { ownerAddress[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(ownerAddress[msg.sender], "Access denied"); _; } /** * @dev Checks if provided address has owner permissions. */ function isOwner(address _addr) public view returns (bool) { return ownerAddress[_addr]; } /** * @dev Grants owner permission to new account. * Can only be called by the current owner. */ function addOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "New owner is empty"); ownerAddress[_newOwner] = true; } /** * @dev Replaces owner permission to new account. * Can only be called by the current owner. */ function setOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "New owner is empty"); ownerAddress[_newOwner] = true; delete(ownerAddress[msg.sender]); } /** * @dev Revokes owner permission from account. * Can only be called by the current owner. */ function removeOwner(address _oldOwner) external onlyOwner { delete(ownerAddress[_oldOwner]); } /** * @dev Throws if called by any account other than the operator. */ modifier onlyOperator() { require(isOperator(msg.sender), "Access denied"); _; } /** * @dev Checks if provided address has operator or owner permissions. */ function isOperator(address _addr) public view returns (bool) { return operatorAddress[_addr] || ownerAddress[_addr]; } /** * @dev Grants operator permission to new account. * Can only be called by the current owner. */ function addOperator(address _newOperator) external onlyOwner { require(_newOperator != address(0), "New operator is empty"); operatorAddress[_newOperator] = true; } /** * @dev Revokes operator permission from account. * Can only be called by the current owner. */ function removeOperator(address _oldOperator) external onlyOwner { delete(operatorAddress[_oldOperator]); } /** * @dev Transfers to _withdrawToAddress all tokens controlled by * contract _tokenContract. */ function withdrawERC20( IERC20 _tokenContract, address _withdrawToAddress ) external onlyOperator { uint256 balance = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_withdrawToAddress, balance); } /** * @dev Allow to withdraw ERC721 tokens from contract itself */ function approveERC721(IERC721 _tokenContract, address _approveToAddress) external onlyOperator { _tokenContract.setApprovalForAll(_approveToAddress, true); } /** * @dev Allow to withdraw ERC1155 tokens from contract itself */ function approveERC1155(IERC1155 _tokenContract, address _approveToAddress) external onlyOperator { _tokenContract.setApprovalForAll(_approveToAddress, true); } /** * @dev Allow to withdraw ETH from contract itself (only by owner) */ function withdrawEth(address payable _withdrawToAddress) external onlyOperator { if (address(this).balance > 0) { _withdrawToAddress.transfer(address(this).balance); } } }
* @dev Allow to withdraw ERC1155 tokens from contract itself/
function approveERC1155(IERC1155 _tokenContract, address _approveToAddress) external onlyOperator { _tokenContract.setApprovalForAll(_approveToAddress, true); }
926,315
[ 1, 7009, 358, 598, 9446, 4232, 39, 2499, 2539, 2430, 628, 6835, 6174, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 654, 39, 2499, 2539, 12, 45, 654, 39, 2499, 2539, 389, 2316, 8924, 16, 1758, 389, 12908, 537, 774, 1887, 13, 203, 3639, 3903, 203, 3639, 1338, 5592, 203, 565, 288, 203, 3639, 389, 2316, 8924, 18, 542, 23461, 1290, 1595, 24899, 12908, 537, 774, 1887, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./ConvexStrategy2Token.sol"; contract ConvexStrategyHBTCMainnet is ConvexStrategy2Token { address public hbtc_unused; // just a differentiator for the bytecode constructor() public {} function initializeStrategy( address _storage, address _vault ) public initializer { address underlying = address(0xb19059ebb43466C323583928285a49f558E572Fd); address rewardPool = address(0x618BD6cBA676a46958c63700C04318c84a7b7c0A); address crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); address wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address hbtcCurveDeposit = address(0x4CA9b3063Ec5866A4B82E437059D2C43d1be596F); ConvexStrategy2Token.initializeBaseStrategy( _storage, underlying, _vault, rewardPool, //rewardPool 8, // Pool id wbtc, 1, //depositArrayPosition hbtcCurveDeposit, 0x00d10Fe4b76cA47E4e5206A93F10205b9C0c42a2, 1000 ); reward2WETH[crv] = [crv, weth]; reward2WETH[cvx] = [cvx, weth]; WETH2deposit = [weth, wbtc]; rewardTokens = [crv, cvx]; useUni[crv] = false; useUni[cvx] = false; useUni[wbtc] = false; } } pragma solidity 0.5.16; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../base/interface/uniswap/IUniswapV2Router02.sol"; import "../../base/interface/IStrategy.sol"; import "../../base/interface/IVault.sol"; import "../../base/upgradability/BaseUpgradeableStrategy.sol"; import "../../base/interface/uniswap/IUniswapV2Pair.sol"; import "./interface/IBooster.sol"; import "./interface/IBaseRewardPool.sol"; import "../../base/interface/curve/ICurveDeposit_2token.sol"; contract ConvexStrategy2Token is IStrategy, BaseUpgradeableStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant uniswapRouterV2 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant sushiswapRouterV2 = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); address public constant booster = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // additional storage slots (on top of BaseUpgradeableStrategy ones) are defined here bytes32 internal constant _POOLID_SLOT = 0x3fd729bfa2e28b7806b03a6e014729f59477b530f995be4d51defc9dad94810b; bytes32 internal constant _DEPOSIT_TOKEN_SLOT = 0x219270253dbc530471c88a9e7c321b36afda219583431e7b6c386d2d46e70c86; bytes32 internal constant _DEPOSIT_RECEIPT_SLOT = 0x414478d5ad7f54ead8a3dd018bba4f8d686ba5ab5975cd376e0c98f98fb713c5; bytes32 internal constant _DEPOSIT_ARRAY_POSITION_SLOT = 0xb7c50ef998211fff3420379d0bf5b8dfb0cee909d1b7d9e517f311c104675b09; bytes32 internal constant _CURVE_DEPOSIT_SLOT = 0xb306bb7adebd5a22f5e4cdf1efa00bc5f62d4f5554ef9d62c1b16327cd3ab5f9; bytes32 internal constant _HODL_RATIO_SLOT = 0xb487e573671f10704ed229d25cf38dda6d287a35872859d096c0395110a0adb1; bytes32 internal constant _HODL_VAULT_SLOT = 0xc26d330f887c749cb38ae7c37873ff08ac4bba7aec9113c82d48a0cf6cc145f2; uint256 public constant hodlRatioBase = 10000; address[] public WETH2deposit; mapping (address => address[]) public reward2WETH; mapping (address => bool) public useUni; address[] public rewardTokens; constructor() public BaseUpgradeableStrategy() { assert(_POOLID_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.poolId")) - 1)); assert(_DEPOSIT_TOKEN_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.depositToken")) - 1)); assert(_DEPOSIT_RECEIPT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.depositReceipt")) - 1)); assert(_DEPOSIT_ARRAY_POSITION_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.depositArrayPosition")) - 1)); assert(_CURVE_DEPOSIT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.curveDeposit")) - 1)); assert(_HODL_RATIO_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.hodlRatio")) - 1)); assert(_HODL_VAULT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.hodlVault")) - 1)); } function initializeBaseStrategy( address _storage, address _underlying, address _vault, address _rewardPool, uint256 _poolID, address _depositToken, uint256 _depositArrayPosition, address _curveDeposit, address _hodlVault, uint256 _hodlRatio ) public initializer { BaseUpgradeableStrategy.initialize( _storage, _underlying, _vault, _rewardPool, weth, 220, // profit sharing numerator. It is 22% because we remove 10% // before conversion. So, (1 - 0.1) * (1 - 0.22) ~= 0.702, or 30% reduction 1000, // profit sharing denominator true, // sell 0, // sell floor 12 hours // implementation change delay ); address _lpt; address _depositReceipt; (_lpt,_depositReceipt,,,,) = IBooster(booster).poolInfo(_poolID); require(_lpt == underlying(), "Pool Info does not match underlying"); require(_depositArrayPosition < 2, "Deposit array position out of bounds"); _setDepositArrayPosition(_depositArrayPosition); _setPoolId(_poolID); _setDepositToken(_depositToken); _setDepositReceipt(_depositReceipt); _setCurveDeposit(_curveDeposit); setHodlRatio(_hodlRatio); setHodlVault(_hodlVault); WETH2deposit = new address[](0); rewardTokens = new address[](0); } function setHodlRatio(uint256 _value) public onlyGovernance { setUint256(_HODL_RATIO_SLOT, _value); } function hodlRatio() public view returns (uint256) { return getUint256(_HODL_RATIO_SLOT); } function setHodlVault(address _address) public onlyGovernance { setAddress(_HODL_VAULT_SLOT, _address); } function hodlVault() public view returns (address) { return getAddress(_HODL_VAULT_SLOT); } function depositArbCheck() public view returns(bool) { return true; } function rewardPoolBalance() internal view returns (uint256 bal) { bal = IBaseRewardPool(rewardPool()).balanceOf(address(this)); } function exitRewardPool() internal { uint256 stakedBalance = rewardPoolBalance(); if (stakedBalance != 0) { IBaseRewardPool(rewardPool()).withdrawAll(true); } uint256 depositBalance = IERC20(depositReceipt()).balanceOf(address(this)); if (depositBalance != 0) { IBooster(booster).withdrawAll(poolId()); } } function partialWithdrawalRewardPool(uint256 amount) internal { IBaseRewardPool(rewardPool()).withdraw(amount, false); //don't claim rewards at this point uint256 depositBalance = IERC20(depositReceipt()).balanceOf(address(this)); if (depositBalance != 0) { IBooster(booster).withdrawAll(poolId()); } } function emergencyExitRewardPool() internal { uint256 stakedBalance = rewardPoolBalance(); if (stakedBalance != 0) { IBaseRewardPool(rewardPool()).withdrawAll(false); //don't claim rewards } uint256 depositBalance = IERC20(depositReceipt()).balanceOf(address(this)); if (depositBalance != 0) { IBooster(booster).withdrawAll(poolId()); } } function unsalvagableTokens(address token) public view returns (bool) { return (token == rewardToken() || token == underlying() || token == depositReceipt()); } function enterRewardPool() internal { uint256 entireBalance = IERC20(underlying()).balanceOf(address(this)); IERC20(underlying()).safeApprove(booster, 0); IERC20(underlying()).safeApprove(booster, entireBalance); IBooster(booster).depositAll(poolId(), true); //deposit and stake } /* * In case there are some issues discovered about the pool or underlying asset * Governance can exit the pool properly * The function is only used for emergency to exit the pool */ function emergencyExit() public onlyGovernance { emergencyExitRewardPool(); _setPausedInvesting(true); } /* * Resumes the ability to invest into the underlying reward pools */ function continueInvesting() public onlyGovernance { _setPausedInvesting(false); } function setDepositLiquidationPath(address [] memory _route) public onlyGovernance { require(_route[0] == weth, "Path should start with WETH"); require(_route[_route.length-1] == depositToken(), "Path should end with depositToken"); WETH2deposit = _route; } function setRewardLiquidationPath(address [] memory _route) public onlyGovernance { require(_route[_route.length-1] == weth, "Path should end with WETH"); bool isReward = false; for(uint256 i = 0; i < rewardTokens.length; i++){ if (_route[0] == rewardTokens[i]) { isReward = true; } } require(isReward, "Path should start with a rewardToken"); reward2WETH[_route[0]] = _route; } function addRewardToken(address _token, address[] memory _path2WETH) public onlyGovernance { require(_path2WETH[_path2WETH.length-1] == weth, "Path should end with WETH"); require(_path2WETH[0] == _token, "Path should start with rewardToken"); rewardTokens.push(_token); reward2WETH[_token] = _path2WETH; } // We assume that all the tradings can be done on Sushiswap function _liquidateReward() internal { if (!sell()) { // Profits can be disabled for possible simplified and rapoolId exit emit ProfitsNotCollected(sell(), false); return; } for(uint256 i = 0; i < rewardTokens.length; i++){ address token = rewardTokens[i]; uint256 rewardBalance = IERC20(token).balanceOf(address(this)); if (rewardBalance == 0 || reward2WETH[token].length < 2) { continue; } if (token == cvx) { uint256 toHodl = rewardBalance.mul(hodlRatio()).div(hodlRatioBase); if (toHodl > 0) { IERC20(cvx).safeTransfer(hodlVault(), toHodl); rewardBalance = rewardBalance.sub(toHodl); if (rewardBalance == 0) { continue; } } } address routerV2; if(useUni[token]) { routerV2 = uniswapRouterV2; } else { routerV2 = sushiswapRouterV2; } IERC20(token).safeApprove(routerV2, 0); IERC20(token).safeApprove(routerV2, rewardBalance); // we can accept 1 as the minimum because this will be called only by a trusted worker IUniswapV2Router02(routerV2).swapExactTokensForTokens( rewardBalance, 1, reward2WETH[token], address(this), block.timestamp ); } uint256 rewardBalance = IERC20(weth).balanceOf(address(this)); notifyProfitInRewardToken(rewardBalance); uint256 remainingRewardBalance = IERC20(rewardToken()).balanceOf(address(this)); if (remainingRewardBalance == 0) { return; } address routerV2; if(useUni[depositToken()]) { routerV2 = uniswapRouterV2; } else { routerV2 = sushiswapRouterV2; } // allow Uniswap to sell our reward IERC20(rewardToken()).safeApprove(routerV2, 0); IERC20(rewardToken()).safeApprove(routerV2, remainingRewardBalance); // we can accept 1 as minimum because this is called only by a trusted role uint256 amountOutMin = 1; IUniswapV2Router02(routerV2).swapExactTokensForTokens( remainingRewardBalance, amountOutMin, WETH2deposit, address(this), block.timestamp ); uint256 tokenBalance = IERC20(depositToken()).balanceOf(address(this)); if (tokenBalance > 0) { depositCurve(); } } function depositCurve() internal { uint256 tokenBalance = IERC20(depositToken()).balanceOf(address(this)); IERC20(depositToken()).safeApprove(curveDeposit(), 0); IERC20(depositToken()).safeApprove(curveDeposit(), tokenBalance); uint256[2] memory depositArray; depositArray[depositArrayPosition()] = tokenBalance; // we can accept 0 as minimum, this will be called only by trusted roles uint256 minimum = 0; ICurveDeposit_2token(curveDeposit()).add_liquidity(depositArray, minimum); } /* * Stakes everything the strategy holds into the reward pool */ function investAllUnderlying() internal onlyNotPausedInvesting { // this check is needed, because most of the SNX reward pools will revert if // you try to stake(0). if(IERC20(underlying()).balanceOf(address(this)) > 0) { enterRewardPool(); } } /* * Withdraws all the asset to the vault */ function withdrawAllToVault() public restricted { if (address(rewardPool()) != address(0)) { exitRewardPool(); } _liquidateReward(); IERC20(underlying()).safeTransfer(vault(), IERC20(underlying()).balanceOf(address(this))); } /* * Withdraws all the asset to the vault */ function withdrawToVault(uint256 amount) public restricted { // Typically there wouldn't be any amount here // however, it is possible because of the emergencyExit uint256 entireBalance = IERC20(underlying()).balanceOf(address(this)); if(amount > entireBalance){ // While we have the check above, we still using SafeMath below // for the peace of mind (in case something gets changed in between) uint256 needToWithdraw = amount.sub(entireBalance); uint256 toWithdraw = Math.min(rewardPoolBalance(), needToWithdraw); partialWithdrawalRewardPool(toWithdraw); } IERC20(underlying()).safeTransfer(vault(), amount); } /* * Note that we currently do not have a mechanism here to include the * amount of reward that is accrued. */ function investedUnderlyingBalance() external view returns (uint256) { return rewardPoolBalance() .add(IERC20(depositReceipt()).balanceOf(address(this))) .add(IERC20(underlying()).balanceOf(address(this))); } /* * Governance or Controller can claim coins that are somehow transferred into the contract * Note that they cannot come in take away coins that are used and defined in the strategy itself */ function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens(token), "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } /* * Get the reward, sell it in exchange for underlying, invest what you got. * It's not much, but it's honest work. * * Note that although `onlyNotPausedInvesting` is not added here, * calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` * when the investing is being paused by governance. */ function doHardWork() external onlyNotPausedInvesting restricted { IBaseRewardPool(rewardPool()).getReward(); _liquidateReward(); investAllUnderlying(); } /** * Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the * simplest possible way. */ function setSell(bool s) public onlyGovernance { _setSell(s); } /** * Sets the minimum amount of CRV needed to trigger a sale. */ function setSellFloor(uint256 floor) public onlyGovernance { _setSellFloor(floor); } // masterchef rewards pool ID function _setPoolId(uint256 _value) internal { setUint256(_POOLID_SLOT, _value); } function poolId() public view returns (uint256) { return getUint256(_POOLID_SLOT); } function _setDepositToken(address _address) internal { setAddress(_DEPOSIT_TOKEN_SLOT, _address); } function depositToken() public view returns (address) { return getAddress(_DEPOSIT_TOKEN_SLOT); } function _setDepositReceipt(address _address) internal { setAddress(_DEPOSIT_RECEIPT_SLOT, _address); } function depositReceipt() public view returns (address) { return getAddress(_DEPOSIT_RECEIPT_SLOT); } function _setDepositArrayPosition(uint256 _value) internal { setUint256(_DEPOSIT_ARRAY_POSITION_SLOT, _value); } function depositArrayPosition() public view returns (uint256) { return getUint256(_DEPOSIT_ARRAY_POSITION_SLOT); } function _setCurveDeposit(address _address) internal { setAddress(_CURVE_DEPOSIT_SLOT, _address); } function curveDeposit() public view returns (address) { return getAddress(_CURVE_DEPOSIT_SLOT); } function finalizeUpgrade() external onlyGovernance { _finalizeUpgrade(); setHodlVault(0x00d10Fe4b76cA47E4e5206A93F10205b9C0c42a2); setHodlRatio(1000); // 10% } } pragma solidity ^0.5.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); } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: 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; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 { 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); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } pragma solidity 0.5.16; interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function depositArbCheck() external view returns(bool); } pragma solidity 0.5.16; interface IVault { function initializeVault( address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) external ; function balanceOf(address) external view returns (uint256); function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); // function store() external view returns (address); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function announceStrategyUpdate(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; } pragma solidity 0.5.16; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./BaseUpgradeableStrategyStorage.sol"; import "../inheritance/ControllableInit.sol"; import "../interface/IController.sol"; import "../interface/IFeeRewardForwarderV6.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract BaseUpgradeableStrategy is Initializable, ControllableInit, BaseUpgradeableStrategyStorage { using SafeMath for uint256; using SafeERC20 for IERC20; event ProfitsNotCollected(bool sell, bool floor); event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); modifier restricted() { require(msg.sender == vault() || msg.sender == controller() || msg.sender == governance(), "The sender has to be the controller, governance, or vault"); _; } // This is only used in `investAllUnderlying()` // The user can still freely withdraw from the strategy modifier onlyNotPausedInvesting() { require(!pausedInvesting(), "Action blocked as the strategy is in emergency state"); _; } constructor() public BaseUpgradeableStrategyStorage() { } function initialize( address _storage, address _underlying, address _vault, address _rewardPool, address _rewardToken, uint256 _profitSharingNumerator, uint256 _profitSharingDenominator, bool _sell, uint256 _sellFloor, uint256 _implementationChangeDelay ) public initializer { ControllableInit.initialize( _storage ); _setUnderlying(_underlying); _setVault(_vault); _setRewardPool(_rewardPool); _setRewardToken(_rewardToken); _setProfitSharingNumerator(_profitSharingNumerator); _setProfitSharingDenominator(_profitSharingDenominator); _setSell(_sell); _setSellFloor(_sellFloor); _setNextImplementationDelay(_implementationChangeDelay); _setPausedInvesting(false); } /** * Schedules an upgrade for this vault's proxy. */ function scheduleUpgrade(address impl) public onlyGovernance { _setNextImplementation(impl); _setNextImplementationTimestamp(block.timestamp.add(nextImplementationDelay())); } function _finalizeUpgrade() internal { _setNextImplementation(address(0)); _setNextImplementationTimestamp(0); } function shouldUpgrade() external view returns (bool, address) { return ( nextImplementationTimestamp() != 0 && block.timestamp > nextImplementationTimestamp() && nextImplementation() != address(0), nextImplementation() ); } // reward notification function notifyProfitInRewardToken(uint256 _rewardBalance) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator()).div(profitSharingDenominator()); emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken()).safeApprove(controller(), 0); IERC20(rewardToken()).safeApprove(controller(), feeAmount); IController(controller()).notifyFee( rewardToken(), feeAmount ); } else { emit ProfitLogInReward(0, 0, block.timestamp); } } function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator()).div(profitSharingDenominator()); uint256 buybackAmount = _rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000); address forwarder = IController(controller()).feeRewardForwarder(); emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken()).safeApprove(forwarder, 0); IERC20(rewardToken()).safeApprove(forwarder, _rewardBalance); IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts( rewardToken(), feeAmount, pool, buybackAmount ); } else { emit ProfitAndBuybackLog(0, 0, block.timestamp); } } } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2020-05-05 */ // File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity 0.5.16; interface IBooster { function deposit(uint256 _pid, uint256 _amount, bool _stake) external; function depositAll(uint256 _pid, bool _stake) external; function withdraw(uint256 _pid, uint256 _amount) external; function withdrawAll(uint256 _pid) external; function poolInfo(uint256 _pid) external view returns (address lpToken, address, address, address, address, bool); function earmarkRewards(uint256 _pid) external; } pragma solidity 0.5.16; interface IBaseRewardPool { function balanceOf(address account) external view returns(uint256 amount); function pid() external view returns (uint256 _pid); function stakingToken() external view returns (address _stakingToken); function getReward() external; function stake(uint256 _amount) external; function stakeAll() external; function withdraw(uint256 amount, bool claim) external; function withdrawAll(bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function withdrawAllAndUnwrap(bool claim) external; } pragma solidity 0.5.16; interface ICurveDeposit_2token { function get_virtual_price() external view returns (uint); function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity( uint256 _amount, uint256[2] calldata amounts ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external payable; function calc_token_amount( uint256[2] calldata amounts, bool deposit ) external view returns(uint); } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity 0.5.16; import "@openzeppelin/upgrades/contracts/Initializable.sol"; contract BaseUpgradeableStrategyStorage { bytes32 internal constant _UNDERLYING_SLOT = 0xa1709211eeccf8f4ad5b6700d52a1a9525b5f5ae1e9e5f9e5a0c2fc23c86e530; bytes32 internal constant _VAULT_SLOT = 0xefd7c7d9ef1040fc87e7ad11fe15f86e1d11e1df03c6d7c87f7e1f4041f08d41; bytes32 internal constant _REWARD_TOKEN_SLOT = 0xdae0aafd977983cb1e78d8f638900ff361dc3c48c43118ca1dd77d1af3f47bbf; bytes32 internal constant _REWARD_POOL_SLOT = 0x3d9bb16e77837e25cada0cf894835418b38e8e18fbec6cfd192eb344bebfa6b8; bytes32 internal constant _SELL_FLOOR_SLOT = 0xc403216a7704d160f6a3b5c3b149a1226a6080f0a5dd27b27d9ba9c022fa0afc; bytes32 internal constant _SELL_SLOT = 0x656de32df98753b07482576beb0d00a6b949ebf84c066c765f54f26725221bb6; bytes32 internal constant _PAUSED_INVESTING_SLOT = 0xa07a20a2d463a602c2b891eb35f244624d9068572811f63d0e094072fb54591a; bytes32 internal constant _PROFIT_SHARING_NUMERATOR_SLOT = 0xe3ee74fb7893020b457d8071ed1ef76ace2bf4903abd7b24d3ce312e9c72c029; bytes32 internal constant _PROFIT_SHARING_DENOMINATOR_SLOT = 0x0286fd414602b432a8c80a0125e9a25de9bba96da9d5068c832ff73f09208a3b; bytes32 internal constant _NEXT_IMPLEMENTATION_SLOT = 0x29f7fcd4fe2517c1963807a1ec27b0e45e67c60a874d5eeac7a0b1ab1bb84447; bytes32 internal constant _NEXT_IMPLEMENTATION_TIMESTAMP_SLOT = 0x414c5263b05428f1be1bfa98e25407cc78dd031d0d3cd2a2e3d63b488804f22e; bytes32 internal constant _NEXT_IMPLEMENTATION_DELAY_SLOT = 0x82b330ca72bcd6db11a26f10ce47ebcfe574a9c646bccbc6f1cd4478eae16b31; bytes32 internal constant _REWARD_CLAIMABLE_SLOT = 0xbc7c0d42a71b75c3129b337a259c346200f901408f273707402da4b51db3b8e7; bytes32 internal constant _MULTISIG_SLOT = 0x3e9de78b54c338efbc04e3a091b87dc7efb5d7024738302c548fc59fba1c34e6; constructor() public { assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.underlying")) - 1)); assert(_VAULT_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.vault")) - 1)); assert(_REWARD_TOKEN_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.rewardToken")) - 1)); assert(_REWARD_POOL_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.rewardPool")) - 1)); assert(_SELL_FLOOR_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.sellFloor")) - 1)); assert(_SELL_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.sell")) - 1)); assert(_PAUSED_INVESTING_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.pausedInvesting")) - 1)); assert(_PROFIT_SHARING_NUMERATOR_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.profitSharingNumerator")) - 1)); assert(_PROFIT_SHARING_DENOMINATOR_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.profitSharingDenominator")) - 1)); assert(_NEXT_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.nextImplementation")) - 1)); assert(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.nextImplementationTimestamp")) - 1)); assert(_NEXT_IMPLEMENTATION_DELAY_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.nextImplementationDelay")) - 1)); assert(_REWARD_CLAIMABLE_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.rewardClaimable")) - 1)); assert(_MULTISIG_SLOT == bytes32(uint256(keccak256("eip1967.strategyStorage.multiSig")) - 1)); } function _setUnderlying(address _address) internal { setAddress(_UNDERLYING_SLOT, _address); } function underlying() public view returns (address) { return getAddress(_UNDERLYING_SLOT); } function _setRewardPool(address _address) internal { setAddress(_REWARD_POOL_SLOT, _address); } function rewardPool() public view returns (address) { return getAddress(_REWARD_POOL_SLOT); } function _setRewardToken(address _address) internal { setAddress(_REWARD_TOKEN_SLOT, _address); } function rewardToken() public view returns (address) { return getAddress(_REWARD_TOKEN_SLOT); } function _setVault(address _address) internal { setAddress(_VAULT_SLOT, _address); } function vault() public view returns (address) { return getAddress(_VAULT_SLOT); } // a flag for disabling selling for simplified emergency exit function _setSell(bool _value) internal { setBoolean(_SELL_SLOT, _value); } function sell() public view returns (bool) { return getBoolean(_SELL_SLOT); } function _setPausedInvesting(bool _value) internal { setBoolean(_PAUSED_INVESTING_SLOT, _value); } function pausedInvesting() public view returns (bool) { return getBoolean(_PAUSED_INVESTING_SLOT); } function _setSellFloor(uint256 _value) internal { setUint256(_SELL_FLOOR_SLOT, _value); } function sellFloor() public view returns (uint256) { return getUint256(_SELL_FLOOR_SLOT); } function _setProfitSharingNumerator(uint256 _value) internal { setUint256(_PROFIT_SHARING_NUMERATOR_SLOT, _value); } function profitSharingNumerator() public view returns (uint256) { return getUint256(_PROFIT_SHARING_NUMERATOR_SLOT); } function _setProfitSharingDenominator(uint256 _value) internal { setUint256(_PROFIT_SHARING_DENOMINATOR_SLOT, _value); } function profitSharingDenominator() public view returns (uint256) { return getUint256(_PROFIT_SHARING_DENOMINATOR_SLOT); } function allowedRewardClaimable() public view returns (bool) { return getBoolean(_REWARD_CLAIMABLE_SLOT); } function _setRewardClaimable(bool _value) internal { setBoolean(_REWARD_CLAIMABLE_SLOT, _value); } function multiSig() public view returns(address) { return getAddress(_MULTISIG_SLOT); } function _setMultiSig(address _address) internal { setAddress(_MULTISIG_SLOT, _address); } // upgradeability function _setNextImplementation(address _address) internal { setAddress(_NEXT_IMPLEMENTATION_SLOT, _address); } function nextImplementation() public view returns (address) { return getAddress(_NEXT_IMPLEMENTATION_SLOT); } function _setNextImplementationTimestamp(uint256 _value) internal { setUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT, _value); } function nextImplementationTimestamp() public view returns (uint256) { return getUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT); } function _setNextImplementationDelay(uint256 _value) internal { setUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT, _value); } function nextImplementationDelay() public view returns (uint256) { return getUint256(_NEXT_IMPLEMENTATION_DELAY_SLOT); } function setBoolean(bytes32 slot, bool _value) internal { setUint256(slot, _value ? 1 : 0); } function getBoolean(bytes32 slot) internal view returns (bool) { return (getUint256(slot) == 1); } function setAddress(bytes32 slot, address _address) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } function setUint256(bytes32 slot, uint256 _value) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _value) } } function getAddress(bytes32 slot) internal view returns (address str) { // solhint-disable-next-line no-inline-assembly assembly { str := sload(slot) } } function getUint256(bytes32 slot) internal view returns (uint256 str) { // solhint-disable-next-line no-inline-assembly assembly { str := sload(slot) } } } pragma solidity 0.5.16; import "./GovernableInit.sol"; // A clone of Governable supporting the Initializable interface and pattern contract ControllableInit is GovernableInit { constructor() public { } function initialize(address _storage) public initializer { GovernableInit.initialize(_storage); } modifier onlyController() { require(Storage(_storage()).isController(msg.sender), "Not a controller"); _; } modifier onlyControllerOrGovernance(){ require((Storage(_storage()).isController(msg.sender) || Storage(_storage()).isGovernance(msg.sender)), "The caller must be controller or governance"); _; } function controller() public view returns (address) { return Storage(_storage()).controller(); } } pragma solidity 0.5.16; interface IController { event SharePriceChangeLog( address indexed vault, address indexed strategy, uint256 oldSharePrice, uint256 newSharePrice, uint256 timestamp ); // [Grey list] // An EOA can safely interact with the system no matter what. // If you're using Metamask, you're using an EOA. // Only smart contracts may be affected by this grey list. // // This contract will not be able to ban any EOA from the system // even if an EOA is being added to the greyList, he/she will still be able // to interact with the whole system as if nothing happened. // Only smart contracts will be affected by being added to the greyList. // This grey list is only used in Vault.sol, see the code there for reference function greyList(address _target) external view returns(bool); function addVaultAndStrategy(address _vault, address _strategy) external; function doHardWork(address _vault) external; function salvage(address _token, uint256 amount) external; function salvageStrategy(address _strategy, address _token, uint256 amount) external; function notifyFee(address _underlying, uint256 fee) external; function profitSharingNumerator() external view returns (uint256); function profitSharingDenominator() external view returns (uint256); function feeRewardForwarder() external view returns(address); function setFeeRewardForwarder(address _value) external; function addHardWorker(address _worker) external; } pragma solidity 0.5.16; interface IFeeRewardForwarderV6 { function poolNotifyFixedTarget(address _token, uint256 _amount) external; function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function profitSharingPool() external view returns (address); function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external; } pragma solidity 0.5.16; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./Storage.sol"; // A clone of Governable supporting the Initializable interface and pattern contract GovernableInit is Initializable { bytes32 internal constant _STORAGE_SLOT = 0xa7ec62784904ff31cbcc32d09932a58e7f1e4476e1d041995b37c917990b16dc; modifier onlyGovernance() { require(Storage(_storage()).isGovernance(msg.sender), "Not governance"); _; } constructor() public { assert(_STORAGE_SLOT == bytes32(uint256(keccak256("eip1967.governableInit.storage")) - 1)); } function initialize(address _store) public initializer { _setStorage(_store); } function _setStorage(address newStorage) private { bytes32 slot = _STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newStorage) } } function setStorage(address _store) public onlyGovernance { require(_store != address(0), "new storage shouldn't be empty"); _setStorage(_store); } function _storage() internal view returns (address str) { bytes32 slot = _STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { str := sload(slot) } } function governance() public view returns (address) { return Storage(_storage()).governance(); } } pragma solidity 0.5.16; contract Storage { address public governance; address public controller; constructor() public { governance = msg.sender; } modifier onlyGovernance() { require(isGovernance(msg.sender), "Not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance shouldn't be empty"); governance = _governance; } function setController(address _controller) public onlyGovernance { require(_controller != address(0), "new controller shouldn't be empty"); controller = _controller; } function isGovernance(address account) public view returns (bool) { return account == governance; } function isController(address account) public view returns (bool) { return account == controller; } }
solhint-disable-next-line no-inline-assembly
function setAddress(bytes32 slot, address _address) internal { assembly { sstore(slot, _address) } }
141,794
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 1887, 12, 3890, 1578, 4694, 16, 1758, 389, 2867, 13, 2713, 288, 203, 565, 19931, 288, 203, 1377, 272, 2233, 12, 14194, 16, 389, 2867, 13, 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, -100, -100, -100, -100, -100, -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: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } //File: node_modules/openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol pragma solidity ^0.4.24; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } //File: node_modules/openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol pragma solidity ^0.4.24; /** * @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 { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } //File: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } //File: node_modules/openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol pragma solidity ^0.4.24; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * 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, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } //File: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } //File: node_modules/openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol pragma solidity ^0.4.24; /** * @title Mintable token * @dev Simple ERC20 Token example, 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); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint 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() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } //File: node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.4.24; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } //File: node_modules/openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol pragma solidity ^0.4.24; /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } //File: contracts/ico/MftToken.sol /** * @title MFT token * * @version 1.0 * @author Validity Labs AG <[email protected]> */ pragma solidity 0.4.24; contract MftToken is BurnableToken, MintableToken, PausableToken { /* solhint-disable */ string public constant name = "MindFire Token"; string public constant symbol = "MFT"; uint8 public constant decimals = 18; /* solhint-enable */ /** * @dev `Checkpoint` is the structure that attaches a block number to a * given value, the block number attached is the one that last changed the value */ struct Checkpoint { // `fromBlock` is the block number that the value was generatedsuper.mint(_to, _value); from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // Tracks the history of the `totalSupply` of the token Checkpoint[] public totalSupplyHistory; /** * `balances` is the map that tracks the balance of each address, in this * contract when the balance changes the block number that the change * occurred is also included in the map */ mapping (address => Checkpoint[]) public balances; /** * @dev Constructor of MftToken that instantiates a new Mintable Pauseable Token */ constructor() public { paused = true; // token should not be transferrable until after all tokens have been issued } /** * @dev allows batch minting through the mint function call * @param _to address[] * @param _value uint256[] */ function batchMint(address[] _to, uint256[] _value) external { require(_to.length == _value.length, "[] len !="); for (uint256 i; i < _to.length; i = i.add(1)) { mint(_to[i], _value[i]); } } /** * @dev Send `_value` tokens to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success) { require(!paused, "token is paused"); doTransfer(msg.sender, _to, _value); return true; } /** * @dev Send `_value` tokens to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _value The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!paused, "token is paused"); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); doTransfer(_from, _to, _value); return true; } /** * @param _owner The address that's balance is being requested * @return The balance of `_owner` at the current block */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /** * @dev `msg.sender` approves `_spender` to spend `_value` tokens on * its behalf. This is a modified version of the ERC20 approve function * to be a little bit safer * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return True if the approval was successful */ function approve(address _spender, uint256 _value) public returns (bool success) { require(!paused, "token is paused"); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0), "allowed not 0"); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev This function makes it easy to read the `allowed[]` map * @param _owner The address of the account that owns the token * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens of _owner that _spender is allowed * to spend */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev This function makes it easy to get the total number of tokens * @return The total number of tokens */ function totalSupply() public constant returns (uint256) { return totalSupplyAt(block.number); } /** * @dev Queries the balance of `_owner` at a specific `_blockNumber` * @param _owner The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at `_blockNumber` */ function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; } else { // This will return the expected balance during normal situations return getValueAt(balances[_owner], _blockNumber); } } /** * @dev Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` */ function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /** * @dev Generates `_value` tokens that are assigned to `_owner` * @param _to The address that will be assigned the new tokens * @param _value The quantity of tokens generated * @return True if the tokens are generated correctly */ function mint(address _to, uint256 _value) public hasMintPermission canMint returns (bool) { uint256 curTotalSupply = totalSupply(); uint256 previousBalanceTo = balanceOf(_to); updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_value)); updateValueAtNow(balances[_to], previousBalanceTo.add(_value)); emit Mint(_to, _value); emit Transfer(0, _to, _value); return true; } /** * @dev called to burn _value of tokens by the msg.sender * @param _value uint256 the amount of tokens to burn */ function burn(uint256 _value) public { uint256 curTotalSupply = totalSupply(); uint256 previousBalanceFrom = balanceOf(msg.sender); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_value)); updateValueAtNow(balances[msg.sender], previousBalanceFrom.sub(_value)); emit Burn(msg.sender, _value); emit Transfer(msg.sender, 0, _value); } /*** INTERNAL FUNCTIONS ***/ /** * @dev This is the actual transfer function * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _value The amount of tokens to be transferred * @return True if the transfer was successful */ function doTransfer(address _from, address _to, uint256 _value) internal { if (_value == 0) { emit Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0)) && (_to != address(this)), "cannot transfer to 0x0 or token contract"); uint256 previousBalanceFrom = balanceOfAt(_from, block.number); // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom.sub(_value)); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); updateValueAtNow(balances[_to], previousBalanceTo.add(_value)); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _value); } /** * @dev `getValueAt` retrieves the number of tokens at a given block number * @param checkpoints The history of values being queried * @param _block The block number to retrieve the value at * @return The number of tokens being queried */ function getValueAt(Checkpoint[] storage checkpoints, uint _block) internal view returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) { return checkpoints[checkpoints.length.sub(1)].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid.sub(1); } } return checkpoints[min].value; } /** * @dev `updateValueAtNow` used to update the `_CheckpointBalances` map and the `_CheckpointTotalSupply` * @param checkpoints The history of data being updated * @param _value The new number of tokens */ function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) { checkpoints.push(Checkpoint(uint128(block.number), uint128(_value))); } else { checkpoints[checkpoints.length.sub(1)].value = uint128(_value); } } }
* @title Burnable Token @dev Token that can be irreversibly burned (destroyed)./
contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); pragma solidity ^0.4.24; function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } }
6,917,134
[ 1, 38, 321, 429, 3155, 225, 3155, 716, 848, 506, 9482, 266, 2496, 24755, 18305, 329, 261, 11662, 329, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 321, 429, 1345, 353, 7651, 1345, 288, 203, 203, 225, 871, 605, 321, 12, 2867, 8808, 18305, 264, 16, 2254, 5034, 460, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 24, 18, 3247, 31, 203, 225, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 565, 389, 70, 321, 12, 3576, 18, 15330, 16, 389, 1132, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 70, 321, 12, 2867, 389, 3350, 83, 16, 2254, 5034, 389, 1132, 13, 2713, 288, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 3350, 83, 19226, 203, 203, 565, 324, 26488, 63, 67, 3350, 83, 65, 273, 324, 26488, 63, 67, 3350, 83, 8009, 1717, 24899, 1132, 1769, 203, 565, 2078, 3088, 1283, 67, 273, 2078, 3088, 1283, 27799, 1717, 24899, 1132, 1769, 203, 565, 3626, 605, 321, 24899, 3350, 83, 16, 389, 1132, 1769, 203, 565, 3626, 12279, 24899, 3350, 83, 16, 1758, 12, 20, 3631, 389, 1132, 1769, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0xbb3c53364CB0Fd3698f3C9aA86BBa5E4062bc2D8/sources/ThinkTankToken.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract ThinkTankToken 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() public { symbol = "TANK"; name = "ThinkTankToken"; decimals = 18; _totalSupply = 1000000; balances[0x4d03Cd7EA8ee83a4f8f739515cfb0432920eaf63] = _totalSupply; emit Transfer(address(0), 0x4d03Cd7EA8ee83a4f8f739515cfb0432920eaf63, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override 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 override 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 override 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 override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
16,867,063
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 935, 754, 56, 2304, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 56, 20201, 14432, 203, 3639, 508, 273, 315, 1315, 754, 56, 2304, 1345, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 15088, 31, 203, 3639, 324, 26488, 63, 20, 92, 24, 72, 4630, 19728, 27, 41, 37, 28, 1340, 10261, 69, 24, 74, 28, 74, 27, 5520, 25, 3600, 8522, 70, 3028, 1578, 29, 3462, 73, 1727, 4449, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 24, 72, 4630, 19728, 27, 41, 37, 28, 1340, 10261, 69, 24, 74, 28, 74, 27, 5520, 25, 3600, 8522, 70, 3028, 1578, 29, 3462, 73, 1727, 4449, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract ReferenceSystemDeFi is IERC20, Ownable { using SafeMath for int; using SafeMath for uint; using SafeMath for uint8; using SafeMath for uint16; using SafeMath for uint256; bool private _growMarketMint; bool private _reduceSupplyFlag; bool private _shouldRewardOwner; enum TransactionType { BURN, MINT, REWARD_MINER, REWARD_OWNER, TRANSFER } uint8 private _ALPHA; uint8 private _decimals; uint8 private _EPSILON; uint8 private _MIN_PERCENTAGE_FACTOR; uint8 private _metric; uint16 private _EXPANSION_RATE; uint16 private _MAX_TX_INTERVAL; uint16 private _MIN_TX_INTERVAL; uint16 private _SALE_RATE; uint16 private _Q; uint16 private _percentageFactor; uint16 private _seedNumber; uint16 private _txNumber; uint128 private _CROWDSALE_DURATION; uint128 private _CONTRACT_TIMESTAMP; uint256 private _marketCapTotalSupply; uint256 private _targetTotalSupply; uint256 private _totalSupply; uint256 private _moreThanOnce; uint256 private _volumeAfter; uint256 private _volumeBefore; address private _stakeHelper; mapping (address => TransactionType) private _txType; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; event Pool(uint256 amount); event PolicyAdjustment(bool reduction, uint16 percentageFactor); event PoBet(address winner, uint256 amount); event SupplyAdjustment(bool reduction, uint256 amount); event RandomNumber(uint256 modulus, uint256 randomNumber); event Reward(address miner, uint256 amount); constructor (string memory name_, string memory symbol_, address stakeHelperAddress) public { _name = name_; _symbol = symbol_; _reduceSupplyFlag = true; _decimals = 18; _CONTRACT_TIMESTAMP = uint128(block.timestamp); _decimals = 18; _ALPHA = 120; _EPSILON = 120; _EXPANSION_RATE = 1000; // 400 --> 0.25 % | 1000 --> 0.1 % _MIN_PERCENTAGE_FACTOR = 100; _MAX_TX_INTERVAL = 144; _MIN_TX_INTERVAL = 12; _CROWDSALE_DURATION = 7889229; // 3 MONTHS _percentageFactor = 100; _SALE_RATE = 250; _shouldRewardOwner = true; _stakeHelper = stakeHelperAddress; _growMarketMint = true; _mint(owner(), 1459240e18); } receive() external payable { require(msg.data.length == 0); crowdsale(msg.sender); } fallback() external payable { require(msg.data.length == 0); crowdsale(msg.sender); } function crowdsale(address beneficiary) public payable { require(block.timestamp.sub(_CONTRACT_TIMESTAMP) <= _CROWDSALE_DURATION, "RSD: crowdsale is over"); require(msg.value.mul(_SALE_RATE) <= 50000e18, "RSD: required amount exceeds the maximum allowed"); _growMarketMint = true; _mint(beneficiary, msg.value.mul(_SALE_RATE).mul(150).div(100)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _txType[msg.sender] = TransactionType.TRANSFER; _transfer(msg.sender, 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(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _txType[msg.sender] = TransactionType.TRANSFER; _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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) || _txType[msg.sender] == TransactionType.REWARD_MINER || _txType[msg.sender] == TransactionType.REWARD_OWNER, "ERC20: transfer to the zero address"); _beforeTokenTransfer(); uint256 amountToTransfer = _adjustSupply(sender, amount); _volumeAfter = _volumeAfter.add(amount); _balances[sender] = _balances[sender].sub(amountToTransfer, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amountToTransfer); emit Transfer(sender, recipient, amountToTransfer); delete amountToTransfer; } function _mint(address account, uint256 amount) internal virtual { _txType[msg.sender] = TransactionType.MINT; require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(); if (_growMarketMint) { _targetTotalSupply = _targetTotalSupply.add(amount); _marketCapTotalSupply = _marketCapTotalSupply.add(amount); _growMarketMint = false; } _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { _txType[msg.sender] = TransactionType.BURN; require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer() internal virtual { if (_txType[msg.sender] == TransactionType.TRANSFER) { _txNumber = uint16(_txNumber.add(1)); _adjustTargetTotalSupply(); } } function _adjustPolicyOptimal() internal virtual { _Q = uint16((_Q.div(1000).mul(uint16(1000).sub(_ALPHA))).add(_metric.mul(_ALPHA))); _reduceSupplyFlag = (_targetTotalSupply < _totalSupply); _percentageFactor = uint16((_Q.div(1000)).add(_MIN_PERCENTAGE_FACTOR)); } function _adjustPolicyRandom() internal virtual { _reduceSupplyFlag = (_randomNumber(2) != 0); _percentageFactor = uint16((_randomNumber(100).add(_MIN_PERCENTAGE_FACTOR))); } function _adjustTargetTotalSupply() internal virtual { if (_txNumber > _randomNumber(_MAX_TX_INTERVAL) && _txNumber > _MIN_TX_INTERVAL) { uint256 delta; _volumeAfter = _volumeAfter.div(_txNumber); // Avg. volume if (_volumeAfter >= _volumeBefore) { delta = ((_volumeAfter.sub(_volumeBefore)).mul(1e18)).div(((_volumeAfter.add(_volumeBefore)).div(2)).add(1)); _targetTotalSupply = _marketCapTotalSupply.sub((_totalSupply.mul(delta)).div(uint256(1e18).mul(100))); } else { delta = ((_volumeBefore.sub(_volumeAfter)).mul(1e18)).div(((_volumeAfter.add(_volumeBefore)).div(2)).add(1)); _targetTotalSupply = _marketCapTotalSupply.add((_totalSupply.mul(delta)).div(uint256(1e18).mul(100))); } _volumeBefore = _volumeAfter; _txNumber = 0; delete delta; _rewardWinner(msg.sender); } } function _adjustSupply(address account, uint256 txAmount) internal virtual returns(uint256) { if (_txType[msg.sender] == TransactionType.TRANSFER) { if (_randomNumber(1000) > _EPSILON) _adjustPolicyOptimal(); else _adjustPolicyRandom(); uint256 adjustedAmount = _calculateSupplyAdjustment(txAmount); uint256 minerAmount = _calculateMinerReward(txAmount); if (_reduceSupplyFlag) { _burn(account, adjustedAmount); txAmount = txAmount.sub(adjustedAmount).sub(minerAmount); } else { _mint(account, adjustedAmount.add(minerAmount)); txAmount = txAmount.add(adjustedAmount.div(2)); } if (_shouldRewardOwner) { uint256 amountOwner = minerAmount.div(117); // _OWNER_PERCENTAGE minerAmount = minerAmount.sub(amountOwner); _rewardMinerAndPool(account, minerAmount); _rewardOwner(account, amountOwner); delete amountOwner; } else { _rewardMinerAndPool(account, minerAmount); } delete adjustedAmount; delete minerAmount; _calculateMetric(); } return txAmount; } function burn(uint256 amount) public { _burn(msg.sender, amount); } function _calculateMinerReward(uint256 amount) internal virtual view returns(uint256) { return amount.div(_percentageFactor.mul(2)); } function _calculateMetric() internal virtual { if (_targetTotalSupply >= _totalSupply) _metric = uint8(log_2((_targetTotalSupply.sub(_totalSupply)).add(1))); else _metric = uint8(log_2((_totalSupply.sub(_targetTotalSupply)).add(1))); _metric = _metric > 100 ? 0 : (100 - _metric); } function _calculateSupplyAdjustment(uint256 amount) internal virtual view returns(uint256) { return amount.div(_percentageFactor); } function generateRandomMoreThanOnce() public { _moreThanOnce = uint256(keccak256(abi.encodePacked( _moreThanOnce, _seedNumber, block.timestamp, block.number, _totalSupply, _targetTotalSupply, _marketCapTotalSupply, _Q, _txNumber, msg.sender))).mod(_targetTotalSupply); } function getCrowdsaleDuration() public view returns(uint128) { return _CROWDSALE_DURATION; } function getExpansionRate() public view returns(uint16) { return _EXPANSION_RATE; } function getMarketCapTotalSupply() public onlyOwner view returns(uint256) { return _marketCapTotalSupply; } function getMoreThanOnceNumber() public onlyOwner view returns(uint256) { return _moreThanOnce; } function getQ() public onlyOwner view returns(uint16) { return _Q; } function getSaleRate() public view returns(uint16) { return _SALE_RATE; } function getSeedNumber() public onlyOwner view returns(uint16) { return _seedNumber; } function getTargetTotalSupply() public onlyOwner view returns(uint256) { return _targetTotalSupply; } // Snippet copied from Stack Exchange function log_2(uint x) public pure returns (uint y) { assembly { let arg := x x := sub(x,1) x := or(x, div(x, 0x02)) x := or(x, div(x, 0x04)) x := or(x, div(x, 0x10)) x := or(x, div(x, 0x100)) x := or(x, div(x, 0x10000)) x := or(x, div(x, 0x100000000)) x := or(x, div(x, 0x10000000000000000)) x := or(x, div(x, 0x100000000000000000000000000000000)) x := add(x, 1) let m := mload(0x40) mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) mstore(0x40, add(m, 0x100)) let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff let shift := 0x100000000000000000000000000000000000000000000000000000000000000 let a := div(mul(x, magic), shift) y := div(mload(add(m,sub(255,a))), shift) y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) } } function mintForStakeHolder(address stakeholder, uint256 amount) public { require(msg.sender == _stakeHelper, "RSD: only stake helper can call this function"); _growMarketMint = true; _mint(stakeholder, amount); } function obtainRandomNumber(uint256 modulus) public { emit RandomNumber(modulus, _randomNumber(modulus)); } function _randomNumber(uint256 modulus) internal virtual returns(uint256) { _moreThanOnce = _moreThanOnce.add(1); return uint256(keccak256(abi.encodePacked( _moreThanOnce, _seedNumber, block.timestamp, block.number, msg.sender))).mod(modulus); } function _rewardMinerAndPool(address account, uint256 amount) internal virtual { _txType[msg.sender] = TransactionType.REWARD_MINER; _transfer(account, address(this), amount.mul(90).div(100)); _transfer(account, block.coinbase, amount.mul(10).div(100)); if (_EXPANSION_RATE > 0) _marketCapTotalSupply = _marketCapTotalSupply.add(amount.div(_EXPANSION_RATE)); emit Pool(amount.mul(90).div(100)); emit Reward(block.coinbase, amount.mul(10).div(100)); } function _rewardOwner(address account, uint256 amount) internal virtual { _txType[msg.sender] = TransactionType.REWARD_OWNER; _transfer(account, owner(), amount); emit Reward(owner(), amount); } // Here PoBet happens function _rewardWinner(address account) internal virtual { if (_randomNumber(2) != 0) { _mint(account, _balances[address(this)]); emit PoBet(account, _balances[address(this)]); _burn(address(this), _balances[address(this)]); } } function shouldRewardOwner(bool should) public onlyOwner { _shouldRewardOwner = should; } function updateCrowdsaleDuration(uint128 timestampDuration) public onlyOwner { _CROWDSALE_DURATION = timestampDuration; } function updateExpansionRate(uint16 expansionRate) public onlyOwner { _EXPANSION_RATE = expansionRate; } function updateMaxTxInterval(uint16 maxTxInterval) public onlyOwner { _MAX_TX_INTERVAL = maxTxInterval; } function updateMinTxInterval(uint16 minTxInterval) public onlyOwner { _MIN_TX_INTERVAL = minTxInterval; } function updateSaleRate(uint16 rate) public onlyOwner { _SALE_RATE = rate; } function updateSeedNumber(uint16 newSeedNumber) public onlyOwner { _seedNumber = newSeedNumber; } function withdrawSales(address payable account, uint256 amount) public onlyOwner { require(address(this).balance >= amount, "RSD: required amount exceeds the balance"); account.transfer(amount); } function withdrawSales(address payable account) public onlyOwner { require(address(this).balance > 0, "RSD: does not have any balance"); account.transfer(address(this).balance); } function withdrawTokensSent(address tokenAddress) public onlyOwner { IERC20 token = IERC20(tokenAddress); if (token.balanceOf(address(this)) > 0) token.transfer(owner(), token.balanceOf(address(this))); } }
400 --> 0.25 % | 1000 --> 0.1 %
_EXPANSION_RATE = 1000;
1,791,206
[ 1, 16010, 15431, 374, 18, 2947, 738, 571, 4336, 15431, 374, 18, 21, 738, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 16109, 1258, 3686, 67, 24062, 273, 4336, 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 ]
./full_match/80001/0xf80F9A8774216d7309558797FF92F9EFF05333D1/sources/contracts/DegenMugen.sol
Address of the player and => the user info
mapping(address => Player) public playerInfo;
868,149
[ 1, 1887, 434, 326, 7291, 471, 516, 326, 729, 1123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 19185, 13, 1071, 7291, 966, 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 ]
./partial_match/42/0x2b80537BD6fca3CDfe42507A01B6EB0Bc2e62B16/sources/P2PLending.sol
delete loans[msg.sender];
function repayLoan(uint amount) public { require(isBorrower(msg.sender), 'You are not an Borrower'); require(balances[msg.sender] >= amount, 'Not enough money on your BankAccount'); require(hasOngoingLoan[msg.sender] == true, 'You do not have an ongoing Loan'); require(ifLoanOpen(msg.sender) == true, 'You have already paid your debt'); address reciever = loans[msg.sender].investor; loans[msg.sender].original_amount -= amount; transfer(reciever, amount); hasOngoingInvestment[reciever] = false; hasOngoingLoan[msg.sender] = false; emit PayBack(msg.sender, reciever, amount, loans[msg.sender].original_amount); }
3,395,064
[ 1, 3733, 437, 634, 63, 3576, 18, 15330, 15533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2071, 528, 1504, 304, 12, 11890, 3844, 13, 1071, 288, 203, 3639, 2583, 12, 291, 38, 15318, 264, 12, 3576, 18, 15330, 3631, 296, 6225, 854, 486, 392, 605, 15318, 264, 8284, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 3844, 16, 296, 1248, 7304, 15601, 603, 3433, 25610, 3032, 8284, 203, 3639, 2583, 12, 5332, 1398, 8162, 1504, 304, 63, 3576, 18, 15330, 65, 422, 638, 16, 296, 6225, 741, 486, 1240, 392, 30542, 3176, 304, 8284, 203, 3639, 2583, 12, 430, 1504, 304, 3678, 12, 3576, 18, 15330, 13, 422, 638, 16, 296, 6225, 1240, 1818, 30591, 3433, 18202, 88, 8284, 203, 540, 203, 3639, 1758, 1950, 1385, 502, 273, 437, 634, 63, 3576, 18, 15330, 8009, 5768, 395, 280, 31, 203, 3639, 437, 634, 63, 3576, 18, 15330, 8009, 8830, 67, 8949, 3947, 3844, 31, 203, 203, 3639, 7412, 12, 3927, 1385, 502, 16, 3844, 1769, 203, 3639, 711, 1398, 8162, 3605, 395, 475, 63, 3927, 1385, 502, 65, 273, 629, 31, 203, 3639, 711, 1398, 8162, 1504, 304, 63, 3576, 18, 15330, 65, 273, 629, 31, 203, 3639, 3626, 13838, 2711, 12, 3576, 18, 15330, 16, 1950, 1385, 502, 16, 3844, 16, 437, 634, 63, 3576, 18, 15330, 8009, 8830, 67, 8949, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts\utils\EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts\utils\Address.sol pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts\GSN\Context.sol pragma solidity ^0.7.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: contracts\access\AccessControl.sol pragma solidity ^0.7.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts\ERC20\IERC20.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\math\SafeMath.sol pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts\ERC20\ERC20.sol pragma solidity ^0.7.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; // StarCurve _symbol = symbol; // XSTAR _decimals = 18; } /** * @dev Returns the name of the ERC20. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the ERC20, 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 ERC20 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 ERC20 contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts\ERC20\ERC20Burnable.sol pragma solidity ^0.7.0; /** * @dev Extension of {ERC20} that allows ERC20 holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: contracts\utils\Pausable.sol pragma solidity ^0.7.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. */ 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 () public { _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()); } } // File: contracts\ERC20\ERC20Pausable.sol pragma solidity ^0.7.0; /** * @dev ERC20 contracts with pausable contracts 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 contracts transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File: contracts\XSTAR.sol pragma solidity ^0.7.0; /** * @dev {ERC20} contracts, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for contracts minting (creation) * - a pauser role that allows to stop all contracts transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract XSTAR is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all contracts transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all contracts transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
* @dev Emitted when the pause is triggered by `account`./* @dev Emitted when the pause is lifted by `account`./* @dev Initializes the contract in unpaused state./
constructor () public { _paused = false; }
5,955,256
[ 1, 1514, 11541, 1347, 326, 11722, 353, 10861, 635, 1375, 4631, 8338, 19, 225, 512, 7948, 1347, 326, 11722, 353, 28080, 329, 635, 1375, 4631, 8338, 19, 225, 10188, 3128, 326, 6835, 316, 640, 8774, 3668, 919, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 1071, 288, 203, 3639, 389, 8774, 3668, 273, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; contract MyBankAccount { mapping(address => uint256) public balanceOf; uint256 bankBalance; address public owner; function MyBankAccount(uint256 initAmount) payable{ //Initial Function owner = msg.sender;//Set the owner to the contract creator. bankBalance = initAmount;//IMPORTANT: initAmount MUST be = to the initial funding amount. } function () payable{ //In case someone sends in money, and does not specify a function. Who doesn't want free money?? //It's too expensive to credit them the Ether in here. Oh well! } function withdraw(uint256 amount) hasMoney notAnOverdraw(amount){ balanceOf[msg.sender] -= amount;//Remove their money first, as according to "withdrawal pattern" msg.sender.transfer(amount);//Send them their money. } function deposit() payable{ bankBalance += msg.value;//Add the deposit to the money that the owner may NOT touch. balanceOf[msg.sender] += msg.value;//Add their deposit to their balance. } function ownerWithdrawal() isOwner{ uint256 extrafunds = this.balance - bankBalance;//Find out if there is any "free money", by subtracting the actual contract's balance from the Ether allocated to user's addresses. if(extrafunds != 0 && (extrafunds-1) > 0){//Is there "free money"? msg.sender.transfer(extrafunds-1);//Send it to the owner! } } modifier hasMoney(){ require(balanceOf[msg.sender] > 0);//If the sender has a balance greater than 0 _; } modifier notAnOverdraw(uint256 val){ require(balanceOf[msg.sender] >= val);//Require sender's withdrawal to be no more than their balance require(this.balance >= val);//Require the withdrawal to not kill the contract :) _; } modifier isOwner(){ require(msg.sender == owner);//Is the msg.sender the owner? _; } //Optional: add these events to notify others when a user withdraws/deposits. Not enabled by default: why is it really necessary? //event depositComplete(address sender, uint256 value); //event withdrawComplete(address sender, uint256 value); //It is up to you whether or not to activate these. Please note: they MUST be called in order to work. }
IMPORTANT: initAmount MUST be = to the initial funding amount.
bankBalance = initAmount;
7,299,559
[ 1, 20445, 6856, 30, 1208, 6275, 10685, 506, 273, 358, 326, 2172, 22058, 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, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 11218, 13937, 273, 1208, 6275, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @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) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @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) { return a - b; } /** * @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) { return a + b; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return block.timestamp; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() { currentTime = block.timestamp; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); PriceRequest storage newPriceRequest = priceRequests[priceRequestId]; newPriceRequest.identifier = identifier; newPriceRequest.time = time; newPriceRequest.lastVotingRound = nextRoundId; newPriceRequest.index = pendingPriceRequests.length; newPriceRequest.ancillaryData = ancillaryData; pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() ExpandedERC20("UMA Voting Token v1", "UMA", 18) ERC20Snapshot() {} function decimals() public view virtual override(ERC20, ExpandedERC20) returns (uint8) { return super.decimals(); } /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override(ERC20) { super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override(ERC20) { super._burn(account, value); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; bytes32 public constant Bridge = "Bridge"; bytes32 public constant GenericHandler = "GenericHandler"; } // 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; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } uint8 _decimals; /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) ERC20(_tokenName, _tokenSymbol) { _decimals = _tokenDecimals; _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } function decimals() public view virtual override(ERC20) returns (uint8) { return _decimals; } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Arrays.sol"; import "../../../utils/Counters.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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); } // 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 "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT 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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals.slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: 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: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(payable(msg.sender), amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic * of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from block.timestamp. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted 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); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > block.timestamp, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { uint8 _decimals; /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _tokenDecimals ) ERC20(_name, _symbol) { _decimals = _tokenDecimals; } function decimals() public view virtual override(ERC20) returns (uint8) { return _decimals; } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0 except for one small change to the imported Pausable and SafeMath contracts. We replaced local implementations with openzeppelin/contracts versions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private view { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private view { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private view { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface for handler contracts that support deposits and deposit executions. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface for Bridge contract. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0 except for the addition of `deposit()` so that this contract can be called from Sink and Source Oracle contracts. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** @title Interface for handler that handles generic deposits and deposit executions. @dev Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } // 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 "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. Copied directly from here: https://github.com/ChainSafe/chainbridge-solidity/releases/tag/v1.0.0 */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../oracle/interfaces/FinderInterface.sol"; import "./IBridge.sol"; import "../oracle/implementation/Constants.sol"; /** * @title Simple implementation of the OracleInterface used to communicate price request data cross-chain between * EVM networks. Can be extended either into a "Source" or "Sink" oracle that specializes in making and resolving * cross-chain price requests, respectivly. The "Source" Oracle is the originator or source of price resolution data * and can only resolve prices already published by the DVM. The "Sink" Oracle receives the price resolution data * from the Source Oracle and makes it available on non-Mainnet chains. The "Sink" Oracle can also be used to trigger * price requests from the DVM on Mainnet. */ abstract contract BeaconOracle { enum RequestState { NeverRequested, Requested, Resolved } struct Price { RequestState state; int256 price; } // Chain ID for this Oracle. uint8 public currentChainID; // Mapping of encoded price requests {identifier, time, ancillaryData} to Price objects. mapping(bytes32 => Price) internal prices; // Finder to provide addresses for DVM system contracts. FinderInterface public finder; event PriceRequestAdded( address indexed requester, uint8 indexed chainID, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event PushedPrice( address indexed pusher, uint8 indexed chainID, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); /** * @notice Constructor. * @param _finderAddress finder to use to get addresses of DVM contracts. */ constructor(address _finderAddress, uint8 _chainID) { finder = FinderInterface(_finderAddress); currentChainID = _chainID; } // We assume that there is only one GenericHandler for this network. modifier onlyGenericHandlerContract() { require( msg.sender == finder.getImplementationAddress(OracleInterfaces.GenericHandler), "Caller must be GenericHandler" ); _; } /** * @notice Enqueues a request (if a request isn't already present) for the given (identifier, time, ancillary data) * pair. Will revert if request has been requested already. */ function _requestPrice( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal { bytes32 priceRequestId = _encodePriceRequest(chainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; if (lookup.state == RequestState.NeverRequested) { // New query, change state to Requested: lookup.state = RequestState.Requested; emit PriceRequestAdded(msg.sender, chainID, identifier, time, ancillaryData); } } /** * @notice Publishes price for a requested query. Will revert if request hasn't been requested yet or has been * resolved already. */ function _publishPrice( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) internal { bytes32 priceRequestId = _encodePriceRequest(chainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Requested, "Price request is not currently pending"); lookup.price = price; lookup.state = RequestState.Resolved; emit PushedPrice(msg.sender, chainID, identifier, time, ancillaryData, lookup.price); } /** * @notice Returns Bridge contract on network. */ function _getBridge() internal view returns (IBridge) { return IBridge(finder.getImplementationAddress(OracleInterfaces.Bridge)); } /** * @notice Returns the convenient way to store price requests, uniquely identified by {chainID, identifier, time, * ancillaryData }. */ function _encodePriceRequest( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal pure returns (bytes32) { return keccak256(abi.encode(chainID, identifier, time, ancillaryData)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./BeaconOracle.sol"; import "../oracle/interfaces/OracleAncillaryInterface.sol"; /** * @title Extension of BeaconOracle that is intended to be deployed on Mainnet to give financial * contracts on non-Mainnet networks the ability to trigger cross-chain price requests to the Mainnet DVM. This contract * is responsible for triggering price requests originating from non-Mainnet, and broadcasting resolved price data * back to those networks. Technically, this contract is more of a Proxy than an Oracle, because it does not implement * the full Oracle interface including the getPrice and requestPrice methods. It's goal is to shuttle price request * functionality between L2 and L1. * @dev The intended client of this contract is some off-chain bot watching for resolved price events on the DVM. Once * that bot sees a price has resolved, it can call `publishPrice()` on this contract which will call the local Bridge * contract to signal to an off-chain relayer to bridge a price request to another network. * @dev This contract must be a registered financial contract in order to call DVM methods. */ contract SourceOracle is BeaconOracle { constructor(address _finderAddress, uint8 _chainID) BeaconOracle(_finderAddress, _chainID) {} /*************************************************************** * Publishing Price Request Data to L2: ***************************************************************/ /** * @notice This is the first method that should be called in order to publish a price request to another network * marked by `sinkChainID`. * @dev Publishes the DVM resolved price for the price request, or reverts if not resolved yet. Will call the * local Bridge's deposit() method which will emit a Deposit event in order to signal to an off-chain * relayer to begin the cross-chain process. */ function publishPrice( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) public { require(_getOracle().hasPrice(identifier, time, ancillaryData), "DVM has not resolved price"); int256 price = _getOracle().getPrice(identifier, time, ancillaryData); _publishPrice(sinkChainID, identifier, time, ancillaryData, price); // Call Bridge.deposit() to initiate cross-chain publishing of price request. _getBridge().deposit( sinkChainID, getResourceId(), _formatMetadata(sinkChainID, identifier, time, ancillaryData, price) ); } /** * @notice This method will ultimately be called after `publishPrice` calls `Bridge.deposit()`, which will call * `GenericHandler.deposit()` and ultimately this method. * @dev This method should basically check that the `Bridge.deposit()` was triggered by a valid publish event. */ function validateDeposit( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) public view { bytes32 priceRequestId = _encodePriceRequest(sinkChainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Resolved, "Price has not been published"); require(lookup.price == price, "Unexpected price published"); } /*************************************************************** * Responding to a Price Request from L2: ***************************************************************/ /** * @notice This method will ultimately be called after a `requestPrice` has been bridged cross-chain from * non-Mainnet to this network via an off-chain relayer. The relayer will call `Bridge.executeProposal` on this * local network, which call `GenericHandler.executeProposal()` and ultimately this method. * @dev This method should prepare this oracle to receive a published price and then forward the price request * to the DVM. Can only be called by the `GenericHandler`. */ function executeRequestPrice( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) public onlyGenericHandlerContract() { _requestPrice(sinkChainID, identifier, time, ancillaryData); _getOracle().requestPrice(identifier, time, ancillaryData); } /** * @notice Convenience method to get cross-chain Bridge resource ID linking this contract with its SinkOracles. * @dev More details about Resource ID's here: https://chainbridge.chainsafe.io/spec/#resource-id * @return bytes32 Hash containing this stored chain ID. */ function getResourceId() public view returns (bytes32) { return keccak256(abi.encode("Oracle", currentChainID)); } /** * @notice Return DVM for this network. */ function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } /** * @notice This helper method is useful for calling Bridge.deposit(). * @dev GenericHandler.deposit() expects data to be formatted as: * len(data) uint256 bytes 0 - 64 * data bytes bytes 64 - END */ function _formatMetadata( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) internal pure returns (bytes memory) { bytes memory metadata = abi.encode(chainID, identifier, time, ancillaryData, price); return abi.encodePacked(metadata.length, metadata); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./BeaconOracle.sol"; import "../oracle/interfaces/OracleAncillaryInterface.sol"; import "../oracle/interfaces/RegistryInterface.sol"; /** * @title Extension of BeaconOracle that is intended to be deployed on non-Mainnet networks to give financial * contracts on those networks the ability to trigger cross-chain price requests to the Mainnet DVM. Also has the * ability to receive published prices from Mainnet. This contract can be treated as the "DVM" for a non-Mainnet * network, because a calling contract can request and access a resolved price request from this contract. * @dev The intended client of this contract is an OptimisticOracle on a non-Mainnet network that needs price * resolution secured by the DVM on Mainnet. If a registered contract, such as the OptimisticOracle, calls * `requestPrice()` on this contract, then it will call the network's Bridge contract to signal to an off-chain * relayer to bridge a price request to Mainnet. */ contract SinkOracle is BeaconOracle, OracleAncillaryInterface { // Chain ID of the Source Oracle that will communicate this contract's price request to the DVM on Mainnet. uint8 public destinationChainID; constructor( address _finderAddress, uint8 _chainID, uint8 _destinationChainID ) BeaconOracle(_finderAddress, _chainID) { destinationChainID = _destinationChainID; } // This assumes that the local network has a Registry that resembles the Mainnet registry. modifier onlyRegisteredContract() { RegistryInterface registry = RegistryInterface(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Caller must be registered"); _; } /*************************************************************** * Bridging a Price Request to L1: ***************************************************************/ /** * @notice This is the first method that should be called in order to bridge a price request to Mainnet. * @dev Can be called only by a Registered contract that is allowed to make DVM price requests. Will mark this * price request as Requested, and therefore able to receive the ultimate price resolution data, and also * calls the local Bridge's deposit() method which will emit a Deposit event in order to signal to an off-chain * relayer to begin the cross-chain process. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { _requestPrice(currentChainID, identifier, time, ancillaryData); // Call Bridge.deposit() to intiate cross-chain price request. _getBridge().deposit( destinationChainID, getResourceId(), _formatMetadata(currentChainID, identifier, time, ancillaryData) ); } /** * @notice This method will ultimately be called after `requestPrice` calls `Bridge.deposit()`, which will call * `GenericHandler.deposit()` and ultimately this method. * @dev This method should basically check that the `Bridge.deposit()` was triggered by a valid price request, * specifically one that has not resolved yet and was called by a registered contract. Without this check, * `Bridge.deposit()` could be called by non-registered contracts to make price requests to the DVM. */ function validateDeposit( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view { bytes32 priceRequestId = _encodePriceRequest(sinkChainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Requested, "Price has not been requested"); } /*************************************************************** * Responding to Price Request Resolution from L1: ***************************************************************/ /** * @notice This method will ultimately be called after a `publishPrice` has been bridged cross-chain from Mainnet * to this network via an off-chain relayer. The relayer will call `Bridge.executeProposal` on this local network, * which call `GenericHandler.executeProposal()` and ultimately this method. * @dev This method should publish the price data for a requested price request. If this method fails for some * reason, then it means that the price was never requested. Can only be called by the `GenericHandler`. */ function executePublishPrice( uint8 sinkChainID, bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) public onlyGenericHandlerContract() { _publishPrice(sinkChainID, identifier, time, ancillaryData, price); } /** * @notice Returns whether a price has resolved for the request. * @return True if a price is available, False otherwise. If true, then getPrice will succeed for the request. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { bytes32 priceRequestId = _encodePriceRequest(currentChainID, identifier, time, ancillaryData); return prices[priceRequestId].state == RequestState.Resolved; } /** * @notice Returns resolved price for the request. * @return int256 Price, or reverts if no resolved price for any reason. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { bytes32 priceRequestId = _encodePriceRequest(currentChainID, identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; require(lookup.state == RequestState.Resolved, "Price has not been resolved"); return lookup.price; } /** * @notice Convenience method to get cross-chain Bridge resource ID linking this contract with the SourceOracle. * @dev More details about Resource ID's here: https://chainbridge.chainsafe.io/spec/#resource-id * @return bytes32 Hash containing the chain ID of the SourceOracle. */ function getResourceId() public view returns (bytes32) { return keccak256(abi.encode("Oracle", destinationChainID)); } /** * @notice This helper method is useful for calling Bridge.deposit(). * @dev GenericHandler.deposit() expects data to be formatted as: * len(data) uint256 bytes 0 - 64 * data bytes bytes 64 - END */ function _formatMetadata( uint8 chainID, bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal pure returns (bytes memory) { bytes memory metadata = abi.encode(chainID, identifier, time, ancillaryData); return abi.encodePacked(metadata.length, metadata); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { using FixedPoint for FixedPoint.Unsigned; mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { using FixedPoint for FixedPoint.Unsigned; mapping(address => FixedPoint.Unsigned) financialProductTransformedPrices; /** * @notice Enables any address to set the transformed pricxe for an associated financial product. * @param financialProduct address of the financial product. * @param transformedPrice the price for the financial product to be used if the contract is pre-expiration. * @dev Note: a) Any address can set identifier transformations b) The price can't be set to blank. * c) A transformed price can only be set once to prevent the deployer from changing it after the fact. * d) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductTransformedPrice(address financialProduct, FixedPoint.Unsigned memory transformedPrice) public nonReentrant() { require(transformedPrice.isGreaterThan(0), "Cant set price of 0"); require(financialProductTransformedPrices[financialProduct].isEqual(0), "Price already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedPrices[financialProduct] = transformedPrice; } /** * @notice Returns the transformed price associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed price for the associated financial product. */ function getTransformedPriceForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductTransformedPrices[financialProduct]; } /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory transformedPrice = financialProductTransformedPrices[msg.sender]; require(transformedPrice.isGreaterThan(0), "Caller has no transformation"); // If price request is made before expiry, return transformed price. Post-expiry, leave unchanged. // if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return transformedPrice; } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { using FixedPoint for FixedPoint.Unsigned; mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. UMA uses 0.8.0 and so a modified version is needed to accomidate this solidity version. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } } // The library below is taken from @uniswap/lib/contracts/libraries/FullMath.sol. It has been modified to work with solidity 0.8 library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = denominator & (~denominator + 1); // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), block.timestamp); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return block.timestamp; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
* @notice Commit a vote for a price request for `identifier` at `time`. @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. Commits can be changed. @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then they can determine the vote pre-reveal. @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. @param time unix timestamp of the price being voted on. @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`./* @notice Submit a batch of commits in a single transaction. @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. Look at `project-root/common/Constants.js` for the tested maximum number of commitments that can fit in one transaction. @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`./* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. @param identifier unique price pair identifier. Eg: BTC/USD price pair. @param time unix timestamp of for the price request. @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. @param encryptedVote offchain encrypted blob containing the voters amount, time and salt./* @notice snapshot the current round's token balances and lock in the inflation rate and GAT. @dev This function can be called multiple times but each round will only every have one snapshot at the time of calling `_freezeRoundVariables`. @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the snapshot./* @notice Reveal a previously committed vote for `identifier` at `time`. @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` that `commitVote()` was called with. Only the committer can reveal their vote. @param identifier voted on in the commit phase. EG BTC/USD price pair. @param time specifies the unix timestamp of the price is being voted on. @param price voted on during the commit phase. @param salt value used to hide the commitment price during the commit phase./* @notice Reveal multiple votes in a single transaction. Look at `project-root/common/Constants.js` for the tested maximum number of reveals. that can fit in one transaction. @dev For more information on reveals, review the comment for `revealVote`. @param reveals array of the Reveal struct which contains an identifier, time, price and salt./* @notice Gets the queries that are being voted on this round. @return pendingRequests `PendingRequest` array containing identifiers and timestamps for all pending requests./* @notice Returns the current voting phase, as a function of the current time. @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }./* @notice Returns the current round ID, as a function of the current time. @return uint256 representing the unique round ID./* @notice Retrieves rewards owed for a set of resolved price requests. @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold (not expired). @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. @param roundId the round from which voting rewards will be retrieved from. @param toRetrieve array of PendingRequests which rewards are retrieved from. @return total amount of rewards returned to the voter./ Voting Owner functions.* @notice Disables this Voting contract in favor of the migrated one. @dev Can only be called by the contract owner. @param newVotingAddress the newly migrated contract address./* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. @dev This method is public because calldata structs are not currently supported by solidity. @param newInflationRate sets the next round's inflation rate./* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. @dev This method is public because calldata structs are not currently supported by solidity. @param newGatPercentage sets the next round's Gat percentage./* @notice Resets the rewards expiration timeout. @dev This change only applies to rounds that have not yet begun. @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards./ SPDX-License-Identifier: AGPL-3.0-only* @title Universal store of current contract time for testing environments./
contract Timer { uint256 private currentTime; function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; function batchCommit(Commitment[] memory commits) public virtual; function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; function snapshotCurrentRound(bytes calldata signature) external virtual; function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; function batchReveal(Reveal[] memory reveals) public virtual; function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); function getCurrentRoundId() external view virtual returns (uint256); function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); function setMigrated(address newVotingAddress) external virtual; function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } pragma solidity ^0.8.0; constructor() { } function setCurrentTime(uint256 time) external { currentTime = time; } function getCurrentTime() public view returns (uint256) { return currentTime; } }
271,765
[ 1, 5580, 279, 12501, 364, 279, 6205, 590, 364, 1375, 5644, 68, 622, 1375, 957, 8338, 225, 1375, 5644, 9191, 1375, 957, 68, 1297, 4325, 358, 279, 6205, 590, 716, 1807, 4551, 316, 326, 3294, 6855, 18, 16854, 1282, 848, 506, 3550, 18, 225, 7897, 2492, 501, 353, 1071, 16, 326, 4286, 903, 506, 283, 537, 18931, 598, 326, 12501, 18, 21572, 333, 353, 326, 2619, 163, 227, 252, 87, 2665, 6885, 16, 331, 352, 414, 1410, 5903, 11827, 4286, 87, 18, 971, 18626, 469, 353, 7752, 358, 7274, 326, 331, 16474, 6205, 471, 21739, 716, 279, 4286, 903, 506, 23312, 16, 1508, 2898, 848, 4199, 326, 12501, 675, 17, 266, 24293, 18, 225, 2756, 30059, 25283, 326, 16015, 12501, 18, 512, 43, 605, 15988, 19, 3378, 40, 6205, 3082, 18, 225, 813, 9753, 2858, 434, 326, 6205, 3832, 331, 16474, 603, 18, 225, 1651, 417, 24410, 581, 5034, 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, 12290, 288, 203, 565, 2254, 5034, 3238, 6680, 31, 203, 203, 565, 445, 3294, 19338, 12, 203, 3639, 1731, 1578, 2756, 16, 203, 3639, 2254, 5034, 813, 16, 203, 3639, 1731, 1578, 1651, 203, 565, 262, 3903, 5024, 31, 203, 203, 565, 445, 2581, 5580, 12, 5580, 475, 8526, 3778, 14335, 13, 1071, 5024, 31, 203, 203, 565, 445, 3294, 1876, 17982, 14678, 19338, 12, 203, 3639, 1731, 1578, 2756, 16, 203, 3639, 2254, 5034, 813, 16, 203, 3639, 1731, 1578, 1651, 16, 203, 3639, 1731, 3778, 6901, 19338, 203, 565, 262, 1071, 5024, 31, 203, 203, 565, 445, 4439, 3935, 11066, 12, 3890, 745, 892, 3372, 13, 3903, 5024, 31, 203, 203, 565, 445, 283, 24293, 19338, 12, 203, 3639, 1731, 1578, 2756, 16, 203, 3639, 2254, 5034, 813, 16, 203, 3639, 509, 5034, 6205, 16, 203, 3639, 509, 5034, 4286, 203, 565, 262, 1071, 5024, 31, 203, 203, 565, 445, 2581, 426, 24293, 12, 426, 24293, 8526, 3778, 283, 537, 1031, 13, 1071, 5024, 31, 203, 203, 565, 445, 1689, 2846, 6421, 1435, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 58, 17128, 979, 71, 737, 814, 1358, 18, 8579, 691, 979, 71, 737, 814, 8526, 3778, 1769, 203, 203, 565, 445, 11031, 1168, 11406, 1435, 3903, 1476, 5024, 1135, 261, 58, 17128, 979, 71, 737, 814, 1358, 18, 11406, 1769, 203, 203, 565, 445, 5175, 11066, 548, 1435, 3903, 1476, 5024, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4614, 17631, 14727, 12, 203, 2 ]
// Sources flattened with hardhat v2.8.3 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File @openzeppelin/contracts/utils/math/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @uniswap/v2-core/contracts/interfaces/[email protected] pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File @uniswap/v2-core/contracts/interfaces/[email protected] pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File contracts/BLUME.sol pragma solidity ^0.8.0; /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } library SafeMathInt { function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns (uint256); /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed(address indexed from, uint256 weiAmount); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn(address indexed to, uint256 weiAmount); } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns (uint256); } /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is Context, ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { } /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(_msgSender(), msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value: _withdrawableDividend, gas: 3000}(""); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return (magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() + magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] - (magnifiedDividendPerShare.mul(value)).toInt256Safe(); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] + (magnifiedDividendPerShare.mul(value)).toInt256Safe(); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } contract ERC20DividendToken is Context, ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; TokenDividendTracker public dividendTracker; uint256 public minTokensBeforeSwap; mapping(address => bool) public isBlacklisted; uint256 public rewardsFee; uint256 public liquidityFee; uint256 public treasuryFee; uint256 public totalFees; address public treasuryAddress; bool public tradingEnabled; // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; // 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; uint256 public maxTxAmount; uint256 public maxWalletAmount; mapping (address => bool) public isExcludedFromLimits; event DeployedDividendTracker( address indexed newAddress ); event UpdateUniswapV2Router( address indexed newAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SendDividends(uint256 tokensSwapped, uint256 amount); event SendDividendsToTreasury(uint256 tokensSwapped, uint256 amount); constructor(string memory name_, string memory symbol_, uint256 totalSupply_, address routerV2_, address treasuryAddress_) ERC20(name_, symbol_) { rewardsFee = 3; liquidityFee = 2; treasuryFee = 10; totalFees = rewardsFee.add(liquidityFee).add(treasuryFee); require(totalFees <= 100, "Total fee is over 100%"); treasuryAddress = treasuryAddress_; minTokensBeforeSwap = 1_000 * (10**18); maxTxAmount = totalSupply_ * 3 * (10**16); // 3% maxWalletAmount = totalSupply_ * (10**17); // 10% deployDividendTracker(routerV2_); _updateUniswapV2Router(routerV2_); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(treasuryAddress, true); excludeFromLimits(owner(), true); excludeFromLimits(address(this), true); excludeFromLimits(treasuryAddress, true); excludeFromLimits(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), totalSupply_ * (10**18)); } receive() external payable {} function excludeFromLimits(address account, bool excluded) public onlyOwner { isExcludedFromLimits[account] = excluded; } function changeMaxTxAmount(uint256 amount) public onlyOwner { maxTxAmount = amount; } function changeMaxWalletAmount(uint256 amount) public onlyOwner { maxWalletAmount = amount; } function setMinTokensBeforeSwap(uint256 amount) external onlyOwner { minTokensBeforeSwap = amount; } function enableTrading(bool enabled) external onlyOwner { tradingEnabled = enabled; } function deployDividendTracker(address _uniswapV2Router) internal { dividendTracker = new TokenDividendTracker(); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(0xdead)); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); emit DeployedDividendTracker(address(dividendTracker)); } function _updateUniswapV2Router(address newAddress) internal { uniswapV2Router = IUniswapV2Router02(newAddress); address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); excludeFromLimits(newAddress, true); uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); emit UpdateUniswapV2Router(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees( address[] calldata accounts, bool excluded ) public onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setTreasuryWallet(address wallet) external onlyOwner { treasuryAddress = wallet; } function setRewardsFee(uint256 value) external onlyOwner { rewardsFee = value; totalFees = rewardsFee.add(liquidityFee).add(treasuryFee); } function setLiquidityFee(uint256 value) external onlyOwner { liquidityFee = value; totalFees = rewardsFee.add(liquidityFee).add(treasuryFee); } function setTreasuryFee(uint256 value) external onlyOwner { treasuryFee = value; totalFees = rewardsFee.add(liquidityFee).add(treasuryFee); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "ERC20DividendToken: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function blacklistAddress(address account, bool value) external onlyOwner { isBlacklisted[account] = value; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require( automatedMarketMakerPairs[pair] != value, "ERC20DividendToken: Automated market maker pair is already set to that value" ); automatedMarketMakerPairs[pair] = value; if (value) { excludeFromLimits(pair, true); dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns (uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function excludeFromDividends(address account) external onlyOwner { dividendTracker.excludeFromDividends(account); } function includeInDividends(address account) external onlyOwner { dividendTracker.includeInDividends(account, balanceOf(account)); } function getAccountDividendsInfo(address account) external view returns ( address, int256, uint256, uint256 ) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, uint256, uint256 ) { return dividendTracker.getAccountAtIndex(index); } function claim() external { dividendTracker.processAccount(_msgSender()); } function getNumberOfDividendTokenHolders() external view returns (uint256) { return dividendTracker.getNumberOfTokenHolders(); } 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(balanceOf(from) >= amount, "ERC20: transfer amount exceeds balance"); require(!isBlacklisted[from] && !isBlacklisted[to], "Blacklisted address"); if ((automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]) && (from != owner() && to != owner())) { require(tradingEnabled, "Trading is not enabled"); } if (!isExcludedFromLimits[from] || (automatedMarketMakerPairs[from] && !isExcludedFromLimits[to])) { require(amount <= maxTxAmount, "Anti-whale: Transfer amount exceeds max limit"); } if (!isExcludedFromLimits[to]) { require(balanceOf(to) + amount <= maxWalletAmount, "Anti-whale: Wallet amount exceeds max limit"); } if (amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= minTokensBeforeSwap; if ( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; if (treasuryFee > 0) { uint256 treasuryTokens = contractTokenBalance.mul(treasuryFee).div(totalFees); swapAndSendDividendsToTreasury(treasuryTokens); } if (liquidityFee > 0) { uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); } if (rewardsFee > 0) { uint256 rewardTokens = balanceOf(address(this)); swapAndSendDividends(rewardTokens); } swapping = false; } bool takeFee = !swapping && (automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]); // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(totalFees).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(from, balanceOf(from)) {} catch {} try dividendTracker.setBalance(to, balanceOf(to)) {} catch {} } function swapAndLiquify(uint256 tokens) private { // split the contract balance into halves uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } 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 address(0xdead), block.timestamp ); } function swapAndSendDividends(uint256 tokens) private { swapTokensForEth(tokens); uint256 dividends = address(this).balance; (bool success,) = payable(address(dividendTracker)).call{value: dividends}(""); if(success) { emit SendDividends(tokens, dividends); } } function swapAndSendDividendsToTreasury(uint256 tokens) private { uint256 initialBalance = address(this).balance; swapTokensForEth(tokens); uint256 dividends = address(this).balance.sub(initialBalance); (bool success,) = payable(treasuryAddress).call{value: dividends}(""); if(success) { emit SendDividendsToTreasury(tokens, dividends); } } } contract TokenDividendTracker is Ownable, DividendPayingToken { using SafeMath for uint256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; mapping(address => bool) public isExcludedFromDividends; uint256 public minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); event IncludeInDividends(address indexed account); event Claim( address indexed account, uint256 amount ); constructor() DividendPayingToken("Dividend_Tracker", "Dividend_Tracker") { minimumTokenBalanceForDividends = 1 * (10**18); } function excludeFromDividends(address account) external onlyOwner { require(!isExcludedFromDividends[account]); isExcludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function includeInDividends(address account, uint256 balance) external onlyOwner { require(isExcludedFromDividends[account]); isExcludedFromDividends[account] = false; _setBalance(account, balance); tokenHoldersMap.set(account, balance); emit IncludeInDividends(account); } function getNumberOfTokenHolders() external view returns (uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, uint256 withdrawableDividends, uint256 totalDividends ) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); } function getAccountAtIndex(uint256 index) public view returns ( address, int256, uint256, uint256 ) { if (index >= tokenHoldersMap.size()) { return (address(0), -1, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function setBalance(address account, uint256 newBalance) external onlyOwner { if (isExcludedFromDividends[account]) { return; } if (newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } } function processAccount(address account) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(payable(account)); if (amount > 0) { emit Claim(account, amount); return true; } return false; } } contract BLUME is ERC20DividendToken { uint256 private _tokenSupply = 10_000_000; /** * @dev Choose proper router address according to your network: * Ethereum mainnet: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D (Uniswap) * BSC mainnet: 0x10ED43C718714eb63d5aA57B78B54704E256024E (PancakeSwap) * BSC testnet: 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 */ address private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor (address _treasuryAddress) ERC20DividendToken("Blume Capital", "BLUME", _tokenSupply, _routerAddress, _treasuryAddress) { // Fees to be set in parent constructor } }
File @openzeppelin/contracts/utils/math/[email protected] OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) CAUTION This version of SafeMath should only be used with Solidity 0.8 or later, because it relies on the compiler's built in overflow checks.* @dev Wrappers over Solidity's arithmetic operations. NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler now has built in overflow checking./
library SafeMath { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
437,268
[ 1, 812, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 15949, 19, 9890, 10477, 18, 18281, 36, 90, 24, 18, 24, 18, 22, 3502, 62, 881, 84, 292, 267, 30131, 331, 24, 18, 24, 18, 21, 261, 5471, 19, 15949, 19, 9890, 10477, 18, 18281, 13, 6425, 13269, 1220, 1177, 434, 14060, 10477, 1410, 1338, 506, 1399, 598, 348, 7953, 560, 374, 18, 28, 578, 5137, 16, 2724, 518, 14719, 281, 603, 326, 5274, 1807, 6650, 316, 9391, 4271, 18, 225, 4266, 10422, 1879, 348, 7953, 560, 1807, 30828, 5295, 18, 5219, 30, 1375, 9890, 10477, 68, 353, 19190, 486, 3577, 5023, 598, 348, 7953, 560, 374, 18, 28, 16, 3241, 326, 5274, 2037, 711, 6650, 316, 9391, 6728, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 3639, 22893, 288, 203, 5411, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 5411, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 5411, 327, 261, 3767, 16, 276, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 3639, 22893, 288, 203, 5411, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 5411, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "@openzeppelin/contracts/access/Ownable.sol"; // erc20 interface for mcb token transfer interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function balanceOf(address owner) external returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); } contract Mining is Ownable { address internal _mcb; int256 internal _budget; int256 internal _rebateRate; address[] internal _pools; mapping(address => address) internal _poolCollaterals; event AddMiningPool(address indexed pool, address indexed collateral); event DelMiningPool(address indexed pool); event RebateRateChange(int256 prevRebateRate, int256 newRebateRate); event MiningBudgetChange(int256 prevBudget, int256 newBudget); event RewardPaid(address indexed user, uint256 reward, uint256 paidBlock); constructor(address mcb) Ownable() { _mcb = mcb; } /** * @notice Get budget of mining * @return int256 The budget of mining */ function getBudget() public view returns (int256) { return _budget; } /** * @notice Get MCB token address * @return address The address of mcb token */ function getMCBToken() public view returns (address) { return _mcb; } /** * @notice Get the rebate rate of mining * @return int256 The rebate rate of mining */ function getRebateRate() public view returns (int256) { return _rebateRate; } /** * @notice Get all mining pool address * @return pools The address of mining pools */ function getMiningPools() public view returns (address[] memory pools) { return _pools; } /** * @notice add mining pool. Can only called by owner. * * @param pool pool address for mining * @param collateral collateral address of pool */ function addMiningPool(address pool, address collateral) external onlyOwner { require(pool != address(0), "invalid pool address"); require(collateral != address(0), "invalid collateral address"); require(_poolCollaterals[pool] == address(0), "pool already exists"); _pools.push(pool); _poolCollaterals[pool] = collateral; emit AddMiningPool(pool, collateral); } /** * @notice delete mining pool. Can only called by owner. * * @param pool pool address for mining */ function delMiningPool(address pool) external onlyOwner { require(pool != address(0), "invalid pool address"); require(_poolCollaterals[pool] != address(0), "pool not exists"); uint256 i = 0; uint256 len = _pools.length; for (i = 0; i < len; i++) { if (_pools[i] == pool) { break; } } delete _pools[i]; delete _poolCollaterals[pool]; emit DelMiningPool(pool); } /** * @notice Set new mining rebate rate. Can only called by owner. * * @param newRebateRate mining rebate rate */ function setRebateRate(int256 newRebateRate) external onlyOwner { require(newRebateRate >= 0, "negative rebate rate"); require(_rebateRate != newRebateRate, "unchanged rate"); emit RebateRateChange(_rebateRate, newRebateRate); _rebateRate = newRebateRate; } /** * @notice Set new mining budget. Can only called by owner. * * @param newBudget mining budget */ function setMingingBudget(int256 newBudget) external onlyOwner { require(newBudget >= 0, "negative budget"); require(_budget != newBudget, "unchanged budget"); emit MiningBudgetChange(_budget, newBudget); _budget = newBudget; } /** * @notice disperse mcb to miners. Can only called by owner. * * @param recipients miner addresses * @param values miner rewards * @param paidBlock blocknumber of calculate reward */ function disperseMCB(address[] memory recipients, uint256[] memory values, uint256 paidBlock) external onlyOwner { IERC20 token = IERC20(_mcb); uint256 total = 0; uint256 len = recipients.length; for (uint256 i = 0; i < len; i++) { total += values[i]; } // transfer mcb token from sender to contract require(token.balanceOf(address(this)) >= total, "mcb balance not enough."); // transfer mcb token to each user for (uint256 i = 0; i < len; i++) { require(token.transfer(recipients[i], values[i]), "transfer failed."); emit RewardPaid(recipients[i], values[i], paidBlock); } } }
* @notice Get all mining pool address @return pools The address of mining pools/
function getMiningPools() public view returns (address[] memory pools) { return _pools; }
5,345,690
[ 1, 967, 777, 1131, 310, 2845, 1758, 327, 16000, 1021, 1758, 434, 1131, 310, 16000, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9555, 310, 16639, 1435, 1071, 1476, 1135, 261, 2867, 8526, 3778, 16000, 13, 288, 203, 3639, 327, 389, 27663, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./interfaces/IRoyalty.sol"; contract VibeDutchAuction is OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; struct CreateReq { // pool name string name; // creator of the pool address creator; // address of sell token address token0; // address of buy token address token1; // total amount of token0 uint amountTotal0; // maximum amount of ETH that creator want to swap uint amountMax1; // minimum amount of ETH that creator want to swap uint amountMin1; // uint amountReserve1; // how many times a bid will decrease it's price uint times; // the timestamp in seconds the pool will open uint openAt; // the timestamp in seconds the pool will be closed uint closeAt; } struct Pool { // pool name string name; // creator of the pool address creator; // address of sell token address token0; // address of buy token address token1; // total amount of sell token uint amountTotal0; // maximum amount of ETH that creator want to swap uint amountMax1; // minimum amount of ETH that creator want to swap uint amountMin1; // uint amountReserve1; // how many times a bid will decrease it's price uint times; // the duration in seconds the pool will be closed uint duration; // the timestamp in seconds the pool will open uint openAt; // the timestamp in seconds the pool will be closed uint closeAt; } address public royaltyAddress; Pool[] public pools; // pool index => amount of sell token has been swap mapping(uint => uint) public amountSwap0P; // pool index => amount of ETH has been swap mapping(uint => uint) public amountSwap1P; // pool index => a flag that if creator is claimed the pool mapping(uint => bool) public creatorClaimedP; mapping(uint => uint) public lowestBidPrice; // bidder address => pool index => whether or not bidder claimed mapping(address => mapping(uint => bool)) public bidderClaimedP; // bidder address => pool index => swapped amount of token0 mapping(address => mapping(uint => uint)) public myAmountSwap0P; // bidder address => pool index => swapped amount of token1 mapping(address => mapping(uint => uint)) public myAmountSwap1P; // creator address => pool index + 1. if the result is 0, the account don't create any pool. mapping(address => uint) public myCreatedP; event Created(uint indexed index, address indexed sender, Pool pool); event Bid(uint indexed index, address indexed sender, uint amount0, uint amount1); event Claimed(uint indexed index, address indexed sender, uint unFilledAmount0); function initialize(address _royaltyAddress) public initializer { super.__Ownable_init(); super.__ReentrancyGuard_init(); royaltyAddress = _royaltyAddress; } function create(CreateReq memory poolReq) external nonReentrant { require(tx.origin == msg.sender, "disallow contract caller"); require(poolReq.amountTotal0 != 0, "the value of amountTotal0 is zero"); require(poolReq.amountMin1 != 0, "the value of amountMax1 is zero"); require(poolReq.amountMax1 != 0, "the value of amountMin1 is zero"); require(poolReq.amountMax1 > poolReq.amountMin1, "amountMax1 should larger than amountMin1"); require(poolReq.openAt <= poolReq.closeAt && poolReq.closeAt.sub(poolReq.openAt) < 7 days, "invalid closed"); require(poolReq.times != 0, "the value of times is zero"); require(bytes(poolReq.name).length <= 15, "the length of name is too long"); uint index = pools.length; // transfer amount of token0 to this contract IERC20Upgradeable _token0 = IERC20Upgradeable(poolReq.token0); uint token0BalanceBefore = _token0.balanceOf(address(this)); _token0.safeTransferFrom(poolReq.creator, address(this), poolReq.amountTotal0); require( _token0.balanceOf(address(this)).sub(token0BalanceBefore) == poolReq.amountTotal0, "not support deflationary token" ); // creator pool Pool memory pool; pool.name = poolReq.name; pool.creator = poolReq.creator; pool.token0 = poolReq.token0; pool.token1 = poolReq.token1; pool.amountTotal0 = poolReq.amountTotal0; pool.amountMax1 = poolReq.amountMax1; pool.amountMin1 = poolReq.amountMin1; // pool.amountReserve1 = poolReq.amountReserve1; pool.times = poolReq.times; pool.duration = poolReq.closeAt.sub(poolReq.openAt); pool.openAt = poolReq.openAt; pool.closeAt = poolReq.closeAt; pools.push(pool); myCreatedP[poolReq.creator] = pools.length; emit Created(index, msg.sender, pool); } function bid( // pool index uint index, // amount of token0 want to bid uint amount0, // amount of token1 uint amount1 ) external payable nonReentrant isPoolExist(index) isPoolNotClosed(index) { require(tx.origin == msg.sender, "disallow contract caller"); Pool memory pool = pools[index]; require(pool.openAt <= block.timestamp, "pool not open"); require(amount0 != 0, "the value of amount0 is zero"); require(amount1 != 0, "the value of amount1 is zero"); require(pool.amountTotal0 > amountSwap0P[index], "swap amount is zero"); // calculate price uint curPrice = currentPrice(index); uint bidPrice = amount1.mul(1 ether).div(amount0); require(bidPrice >= curPrice, "the bid price is lower than the current price"); if (lowestBidPrice[index] == 0 || lowestBidPrice[index] > bidPrice) { lowestBidPrice[index] = bidPrice; } address token1 = pool.token1; if (token1 == address(0)) { require(amount1 == msg.value, "invalid ETH amount"); } else { IERC20Upgradeable(token1).safeTransferFrom(msg.sender, address(this), amount1); } _swap(msg.sender, index, amount0, amount1); emit Bid(index, msg.sender, amount0, amount1); } function creatorClaim(uint index) external nonReentrant isPoolExist(index) isPoolClosed(index) { require(isCreator(msg.sender, index), "sender is not pool creator"); require(!creatorClaimedP[index], "creator has claimed this pool"); creatorClaimedP[index] = true; // remove ownership of this pool from creator delete myCreatedP[msg.sender]; // calculate un-filled amount0 Pool memory pool = pools[index]; uint unFilledAmount0 = pool.amountTotal0.sub(amountSwap0P[index]); if (unFilledAmount0 > 0) { // transfer un-filled amount of token0 back to creator IERC20Upgradeable(pool.token0).safeTransfer(pool.creator, unFilledAmount0); } // send token1 to creator uint amount1 = lowestBidPrice[index].mul(amountSwap0P[index]).div(1 ether); if (amount1 > 0) { IRoyalty royaltyContract = IRoyalty(royaltyAddress); uint royalty = royaltyContract.calculateRoyalty(amount1); uint _actualAmount1 = amount1.sub(royalty); if (pool.token1 == address(0)) { if (_actualAmount1 > 0) { payable(pool.creator).transfer(_actualAmount1); } royaltyContract.chargeRoyaltyETH{value: royalty}(royalty); } else { IERC20Upgradeable(pool.token1).safeTransfer(pool.creator, _actualAmount1); IERC20Upgradeable(pool.token1).safeApprove(royaltyAddress, royalty); royaltyContract.chargeRoyaltyERC20(pool.token1, address(this), royalty); } } emit Claimed(index, pool.creator, unFilledAmount0); } function bidderClaim(uint index) external nonReentrant isPoolExist(index) isPoolClosed(index) { address bidder = msg.sender; require(!bidderClaimedP[bidder][index], "bidder has claimed this pool"); bidderClaimedP[bidder][index] = true; Pool memory pool = pools[index]; // send token0 to bidder if (myAmountSwap0P[bidder][index] > 0) { IERC20Upgradeable(pool.token0).safeTransfer(bidder, myAmountSwap0P[bidder][index]); } // send unfilled token1 to bidder uint actualAmount1 = lowestBidPrice[index].mul(myAmountSwap0P[bidder][index]).div(1 ether); uint unfilledAmount1 = myAmountSwap1P[bidder][index].sub(actualAmount1); if (unfilledAmount1 > 0) { if (pool.token1 == address(0)) { payable(bidder).transfer(unfilledAmount1); } else { IERC20Upgradeable(pool.token1).safeTransfer(bidder, unfilledAmount1); } } } function _swap(address sender, uint index, uint amount0, uint amount1) private { Pool memory pool = pools[index]; uint _amount0 = pool.amountTotal0.sub(amountSwap0P[index]); uint _amount1 = 0; uint _excessAmount1 = 0; // check if amount0 is exceeded if (_amount0 < amount0) { _amount1 = _amount0.mul(amount1).div(amount0); _excessAmount1 = amount1.sub(_amount1); } else { _amount0 = amount0; _amount1 = amount1; } myAmountSwap0P[sender][index] = myAmountSwap0P[sender][index].add(_amount0); myAmountSwap1P[sender][index] = myAmountSwap1P[sender][index].add(_amount1); amountSwap0P[index] = amountSwap0P[index].add(_amount0); amountSwap1P[index] = amountSwap1P[index].add(_amount1); // send excess amount of token1 back to sender if (_excessAmount1 > 0) { if (pool.token1 == address(0)) { payable(sender).transfer(_excessAmount1); } else { IERC20Upgradeable(pool.token1).safeTransfer(sender, _excessAmount1); } } } function isCreator(address target, uint index) private view returns (bool) { if (pools[index].creator == target) { return true; } return false; } function currentPrice(uint index) public view returns (uint) { Pool memory pool = pools[index]; uint _amount1 = pool.amountMin1; uint realTimes = pool.times.add(1); if (block.timestamp < pool.closeAt) { uint stepInSeconds = pool.duration.div(realTimes); if (stepInSeconds != 0) { uint remainingTimes = pool.closeAt.sub(block.timestamp).sub(1).div(stepInSeconds); if (remainingTimes != 0) { _amount1 = pool.amountMax1.sub(pool.amountMin1) .mul(remainingTimes).div(pool.times) .add(pool.amountMin1); } } } return _amount1.mul(1 ether).div(pool.amountTotal0); } function nextRoundInSeconds(uint index) public view returns (uint) { Pool memory pool = pools[index]; if (block.timestamp >= pool.closeAt) return 0; uint realTimes = pool.times.add(1); uint stepInSeconds = pool.duration.div(realTimes); if (stepInSeconds == 0) return 0; uint remainingTimes = pool.closeAt.sub(block.timestamp).sub(1).div(stepInSeconds); return pool.closeAt.sub(remainingTimes.mul(stepInSeconds)).sub(block.timestamp); } function getPoolCount() public view returns (uint) { return pools.length; } modifier isPoolClosed(uint index) { require(pools[index].closeAt <= block.timestamp, "this pool is not closed"); _; } modifier isPoolNotClosed(uint index) { require(pools[index].closeAt > block.timestamp, "this pool is closed"); _; } modifier isPoolNotCreate(address target) { if (myCreatedP[target] > 0) { revert("a pool has created by this address"); } _; } modifier isPoolExist(uint index) { require(index < pools.length, "this pool does not exist"); _; } }
remove ownership of this pool from creator calculate un-filled amount0 transfer un-filled amount of token0 back to creator
function creatorClaim(uint index) external nonReentrant isPoolExist(index) isPoolClosed(index) { require(isCreator(msg.sender, index), "sender is not pool creator"); require(!creatorClaimedP[index], "creator has claimed this pool"); creatorClaimedP[index] = true; delete myCreatedP[msg.sender]; Pool memory pool = pools[index]; uint unFilledAmount0 = pool.amountTotal0.sub(amountSwap0P[index]); if (unFilledAmount0 > 0) { IERC20Upgradeable(pool.token0).safeTransfer(pool.creator, unFilledAmount0); } if (amount1 > 0) { IRoyalty royaltyContract = IRoyalty(royaltyAddress); uint royalty = royaltyContract.calculateRoyalty(amount1); uint _actualAmount1 = amount1.sub(royalty); if (pool.token1 == address(0)) { if (_actualAmount1 > 0) { payable(pool.creator).transfer(_actualAmount1); } IERC20Upgradeable(pool.token1).safeTransfer(pool.creator, _actualAmount1); IERC20Upgradeable(pool.token1).safeApprove(royaltyAddress, royalty); royaltyContract.chargeRoyaltyERC20(pool.token1, address(this), royalty); } } emit Claimed(index, pool.creator, unFilledAmount0); }
12,558,725
[ 1, 4479, 23178, 434, 333, 2845, 628, 11784, 4604, 640, 17, 13968, 3844, 20, 7412, 640, 17, 13968, 3844, 434, 1147, 20, 1473, 358, 11784, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11784, 9762, 12, 11890, 770, 13, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 353, 2864, 4786, 12, 1615, 13, 203, 3639, 353, 2864, 7395, 12, 1615, 13, 203, 565, 288, 203, 3639, 2583, 12, 291, 10636, 12, 3576, 18, 15330, 16, 770, 3631, 315, 15330, 353, 486, 2845, 11784, 8863, 203, 3639, 2583, 12, 5, 20394, 9762, 329, 52, 63, 1615, 6487, 315, 20394, 711, 7516, 329, 333, 2845, 8863, 203, 3639, 11784, 9762, 329, 52, 63, 1615, 65, 273, 638, 31, 203, 203, 3639, 1430, 3399, 6119, 52, 63, 3576, 18, 15330, 15533, 203, 203, 3639, 8828, 3778, 2845, 273, 16000, 63, 1615, 15533, 203, 3639, 2254, 640, 29754, 6275, 20, 273, 2845, 18, 8949, 5269, 20, 18, 1717, 12, 8949, 12521, 20, 52, 63, 1615, 19226, 203, 3639, 309, 261, 318, 29754, 6275, 20, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 10784, 429, 12, 6011, 18, 2316, 20, 2934, 4626, 5912, 12, 6011, 18, 20394, 16, 640, 29754, 6275, 20, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 8949, 21, 405, 374, 13, 288, 203, 5411, 15908, 13372, 15006, 721, 93, 15006, 8924, 273, 15908, 13372, 15006, 12, 3800, 15006, 1887, 1769, 203, 5411, 2254, 721, 93, 15006, 273, 721, 93, 15006, 8924, 18, 11162, 54, 13372, 15006, 12, 8949, 21, 1769, 203, 5411, 2254, 389, 18672, 6275, 21, 273, 3844, 21, 18, 1717, 12, 3800, 15006, 1769, 203, 5411, 309, 261, 6011, 18, 2316, 21, 422, 1758, 12, 20, 3719, 288, 203, 7734, 2 ]
pragma solidity ^0.4.8; import '../../gmo/contracts/VersionLogic.sol'; import './Demo.sol'; import './Demo_v1.sol'; import './TokenSample.sol'; contract DemoLogic_v1 is VersionLogic, Demo { // This is a sample contract, so don't create event contract event CreateToken(address _token); function DemoLogic_v1(ContractNameService _cns) VersionLogic (_cns, CONTRACT_NAME) {} function createToken(address _caller, bytes32 _simbol, bytes32 _name, uint _tokenSupply) onlyByVersionContractOrLogic { address token = new TokenSample(_caller, _simbol, _name, _tokenSupply); CreateToken(token); } function getNonce(address _tokenAddress, address _addr) constant returns (uint nonce) { return TokenSample(_tokenAddress).nonceOf(_addr); } function send(address _tokenAddress, address _to, uint _amount, uint _nonce, bytes _sign) onlyByVersionContractOrLogic { assert(TokenSample(_tokenAddress).transferWithSign(_to, _amount, _nonce, _sign)); } }
This is a sample contract, so don't create event contract
contract DemoLogic_v1 is VersionLogic, Demo { event CreateToken(address _token); function DemoLogic_v1(ContractNameService _cns) VersionLogic (_cns, CONTRACT_NAME) {} function createToken(address _caller, bytes32 _simbol, bytes32 _name, uint _tokenSupply) onlyByVersionContractOrLogic { address token = new TokenSample(_caller, _simbol, _name, _tokenSupply); CreateToken(token); } function getNonce(address _tokenAddress, address _addr) constant returns (uint nonce) { return TokenSample(_tokenAddress).nonceOf(_addr); } function send(address _tokenAddress, address _to, uint _amount, uint _nonce, bytes _sign) onlyByVersionContractOrLogic { assert(TokenSample(_tokenAddress).transferWithSign(_to, _amount, _nonce, _sign)); } }
947,940
[ 1, 2503, 353, 279, 3296, 6835, 16, 1427, 2727, 1404, 752, 871, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 27744, 83, 20556, 67, 90, 21, 353, 4049, 20556, 16, 27744, 83, 288, 203, 565, 871, 1788, 1345, 12, 2867, 389, 2316, 1769, 203, 203, 203, 565, 445, 27744, 83, 20556, 67, 90, 21, 12, 8924, 461, 1179, 389, 71, 2387, 13, 4049, 20556, 261, 67, 71, 2387, 16, 8020, 2849, 1268, 67, 1985, 13, 2618, 203, 565, 445, 752, 1345, 12, 2867, 389, 16140, 16, 1731, 1578, 389, 9812, 31697, 16, 1731, 1578, 389, 529, 16, 2254, 389, 2316, 3088, 1283, 13, 1338, 858, 1444, 8924, 1162, 20556, 288, 203, 3639, 1758, 1147, 273, 394, 3155, 8504, 24899, 16140, 16, 389, 9812, 31697, 16, 389, 529, 16, 389, 2316, 3088, 1283, 1769, 203, 3639, 1788, 1345, 12, 2316, 1769, 203, 565, 289, 203, 203, 565, 445, 336, 13611, 12, 2867, 389, 2316, 1887, 16, 1758, 389, 4793, 13, 5381, 1135, 261, 11890, 7448, 13, 288, 203, 3639, 327, 3155, 8504, 24899, 2316, 1887, 2934, 12824, 951, 24899, 4793, 1769, 203, 565, 289, 203, 203, 565, 445, 1366, 12, 2867, 389, 2316, 1887, 16, 1758, 389, 869, 16, 2254, 389, 8949, 16, 2254, 389, 12824, 16, 1731, 389, 2977, 13, 1338, 858, 1444, 8924, 1162, 20556, 288, 203, 3639, 1815, 12, 1345, 8504, 24899, 2316, 1887, 2934, 13866, 1190, 2766, 24899, 869, 16, 389, 8949, 16, 389, 12824, 16, 389, 2977, 10019, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache License, Version 2.0 pragma solidity ^0.6.10; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { IIndexModule } from "../interfaces/IIndexModule.sol"; import { IStreamingFeeModule } from "../interfaces/IStreamingFeeModule.sol"; import { MutualUpgrade } from "../lib/MutualUpgrade.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; import { TimeLockUpgrade } from "../lib/TimeLockUpgrade.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract ICManager is TimeLockUpgrade, MutualUpgrade { using Address for address; using SafeMath for uint256; using PreciseUnitMath for uint256; /* ============ Events ============ */ event FeesAccrued( uint256 _totalFees, uint256 _operatorTake, uint256 _methodologistTake ); /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken operator */ modifier onlyOperator() { require(msg.sender == operator, "Must be operator"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist() { require(msg.sender == methodologist, "Must be methodologist"); _; } /* ============ State Variables ============ */ // Instance of SetToken ISetToken public setToken; // Address of IndexModule for managing rebalances IIndexModule public indexModule; // Address of StreamingFeeModule IStreamingFeeModule public feeModule; // Address of operator address public operator; // Address of methodologist address public methodologist; // Percent in 1e18 of streamingFees sent to operator uint256 public operatorFeeSplit; /* ============ Constructor ============ */ constructor( ISetToken _setToken, IIndexModule _indexModule, IStreamingFeeModule _feeModule, address _operator, address _methodologist, uint256 _operatorFeeSplit ) public { require( _operatorFeeSplit <= PreciseUnitMath.preciseUnit(), "Operator Fee Split must be less than 1e18" ); setToken = _setToken; indexModule = _indexModule; feeModule = _feeModule; operator = _operator; methodologist = _methodologist; operatorFeeSplit = _operatorFeeSplit; } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Start rebalance in IndexModule. Set new target units, zeroing out any units for components being removed from index. * Log position multiplier to adjust target units in case fees are accrued. * * @param _newComponents Array of new components to add to allocation * @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of component * @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of component, * if component being removed set to 0. * @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units * if fees accrued */ function startRebalance( address[] calldata _newComponents, uint256[] calldata _newComponentsTargetUnits, uint256[] calldata _oldComponentsTargetUnits, uint256 _positionMultiplier ) external onlyOperator { indexModule.startRebalance(_newComponents, _newComponentsTargetUnits, _oldComponentsTargetUnits, _positionMultiplier); } /** * OPERATOR ONLY: Set trade maximums for passed components * * @param _components Array of components * @param _tradeMaximums Array of trade maximums mapping to correct component */ function setTradeMaximums( address[] calldata _components, uint256[] calldata _tradeMaximums ) external onlyOperator { indexModule.setTradeMaximums(_components, _tradeMaximums); } /** * OPERATOR ONLY: Set exchange for passed components * * @param _components Array of components * @param _exchanges Array of exchanges mapping to correct component, uint256 used to signify exchange */ function setAssetExchanges( address[] calldata _components, uint256[] calldata _exchanges ) external onlyOperator { indexModule.setExchanges(_components, _exchanges); } /** * OPERATOR ONLY: Set exchange for passed components * * @param _components Array of components * @param _coolOffPeriods Array of cool off periods to correct component */ function setCoolOffPeriods( address[] calldata _components, uint256[] calldata _coolOffPeriods ) external onlyOperator { indexModule.setCoolOffPeriods(_components, _coolOffPeriods); } /** * OPERATOR ONLY: Toggle ability for passed addresses to trade from current state * * @param _traders Array trader addresses to toggle status * @param _statuses Booleans indicating if matching trader can trade */ function updateTraderStatus( address[] calldata _traders, bool[] calldata _statuses ) external onlyOperator { indexModule.updateTraderStatus(_traders, _statuses); } /** * OPERATOR ONLY: Toggle whether anyone can trade, bypassing the traderAllowList * * @param _status Boolean indicating if anyone can trade */ function updateAnyoneTrade(bool _status) external onlyOperator { indexModule.updateAnyoneTrade(_status); } /** * Accrue fees from streaming fee module and transfer tokens to operator / methodologist addresses based on fee split */ function accrueFeeAndDistribute() public { feeModule.accrueFee(setToken); uint256 setTokenBalance = setToken.balanceOf(address(this)); uint256 operatorTake = setTokenBalance.preciseMul(operatorFeeSplit); uint256 methodologistTake = setTokenBalance.sub(operatorTake); setToken.transfer(operator, operatorTake); setToken.transfer(methodologist, methodologistTake); emit FeesAccrued(setTokenBalance, operatorTake, methodologistTake); } /** * OPERATOR OR METHODOLOGIST ONLY: Update the SetToken manager address. Operator and Methodologist must each call * this function to execute the update. * * @param _newManager New manager address */ function updateManager(address _newManager) external mutualUpgrade(operator, methodologist) { setToken.setManager(_newManager); } /** * OPERATOR ONLY: Add a new module to the SetToken. * * @param _module New module to add */ function addModule(address _module) external onlyOperator { setToken.addModule(_module); } /** * OPERATOR ONLY: Interact with a module registered on the SetToken. Cannot be used to call functions in the * fee module, due to ability to bypass methodologist permissions to update streaming fee. * * @param _module Module to interact with * @param _data Byte data of function to call in module */ function interactModule(address _module, bytes calldata _data) external onlyOperator { require(_module != address(feeModule), "Must not be fee module"); // Invoke call to module, assume value will always be 0 _module.functionCallWithValue(_data, 0); } /** * OPERATOR ONLY: Remove a new module from the SetToken. * * @param _module Module to remove */ function removeModule(address _module) external onlyOperator { setToken.removeModule(_module); } /** * METHODOLOGIST ONLY: Update the streaming fee for the SetToken. Subject to timelock period agreed upon by the * operator and methodologist * * @param _newFee New streaming fee percentage */ function updateStreamingFee(uint256 _newFee) external timeLockUpgrade onlyMethodologist { feeModule.updateStreamingFee(setToken, _newFee); } /** * OPERATOR OR METHODOLOGIST ONLY: Update the fee recipient address. Operator and Methodologist must each call * this function to execute the update. * * @param _newFeeRecipient New fee recipient address */ function updateFeeRecipient(address _newFeeRecipient) external mutualUpgrade(operator, methodologist) { feeModule.updateFeeRecipient(setToken, _newFeeRecipient); } /** * OPERATOR OR METHODOLOGIST ONLY: Update the fee split percentage. Operator and Methodologist must each call * this function to execute the update. * * @param _newFeeSplit New fee split percentage */ function updateFeeSplit(uint256 _newFeeSplit) external mutualUpgrade(operator, methodologist) { require( _newFeeSplit <= PreciseUnitMath.preciseUnit(), "Operator Fee Split must be less than 1e18" ); // Accrue fee to operator and methodologist prior to new fee split accrueFeeAndDistribute(); operatorFeeSplit = _newFeeSplit; } /** * OPERATOR ONLY: Update the index module * * @param _newIndexModule New index module */ function updateIndexModule(IIndexModule _newIndexModule) external onlyOperator { indexModule = _newIndexModule; } /** * METHODOLOGIST ONLY: Update the methodologist address * * @param _newMethodologist New methodologist address */ function updateMethodologist(address _newMethodologist) external onlyMethodologist { methodologist = _newMethodologist; } /** * OPERATOR ONLY: Update the operator address * * @param _newOperator New operator address */ function updateOperator(address _newOperator) external onlyOperator { operator = _newOperator; } /** * OPERATOR OR METHODOLOGIST ONLY: Update the timelock period for updating the streaming fee percentage. * Operator and Methodologist must each call this function to execute the update. * * @param _newTimeLockPeriod New timelock period in seconds */ function setTimeLockPeriod(uint256 _newTimeLockPeriod) external override mutualUpgrade(operator, methodologist) { timeLockPeriod = _newTimeLockPeriod; } }
* OPERATOR OR METHODOLOGIST ONLY: Update the fee recipient address. Operator and Methodologist must each call this function to execute the update. @param _newFeeRecipient New fee recipient address/
function updateFeeRecipient(address _newFeeRecipient) external mutualUpgrade(operator, methodologist) { feeModule.updateFeeRecipient(setToken, _newFeeRecipient); }
1,010,038
[ 1, 26110, 4869, 10078, 2311, 4842, 5511, 20747, 30, 2315, 326, 14036, 8027, 1758, 18, 11097, 471, 2985, 3966, 376, 1297, 1517, 745, 333, 445, 358, 1836, 326, 1089, 18, 225, 389, 2704, 14667, 18241, 6647, 1166, 14036, 8027, 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, 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, 1089, 14667, 18241, 12, 2867, 389, 2704, 14667, 18241, 13, 3903, 4318, 1462, 10784, 12, 9497, 16, 707, 3966, 376, 13, 288, 203, 3639, 14036, 3120, 18, 2725, 14667, 18241, 12, 542, 1345, 16, 389, 2704, 14667, 18241, 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 ]
./full_match/4/0xa3D6A24932F313799F66b5a5C4c1E58B5AD5542D/sources/contracts/BEP20.sol
* @dev Implementation of the {IBEP20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {BEP20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of BEP20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IBEP20-approve}./
contract BEP20 is Context, IBEP20, IBEP20Metadata { 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 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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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, "BEP20: decreased allowance below zero")); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "BEP20: 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), "BEP20: 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), "BEP20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BEP20: 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), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } ) internal virtual {} }
13,358,268
[ 1, 13621, 434, 326, 288, 45, 5948, 52, 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, 5948, 52, 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, 9722, 52, 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, 9722, 52, 3462, 353, 1772, 16, 467, 5948, 52, 3462, 16, 467, 5948, 52, 3462, 2277, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 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, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/utils/Context.sol"; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; contract LoveToken is Context, IERC20, Ownable { using SafeMath for uint256; uint256 public constant INITIAL_REWARD = 500 * (10 ** 18); address private _dudesAddress; address private _sistasAddress; address private _allowedBurner; uint256 public emissionStart; uint256 public emissionEnd; uint256 public emissionPerDay = 6 * (10 ** 18); mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _balances; mapping(uint256 => uint256) private _lastClaimDudes; mapping(uint256 => uint256) private _lastClaimSistas; uint256 private _totalSupply; uint8 private _decimals; string private _name; string private _symbol; constructor (string memory name_, string memory symbol_, address dudesAddress, address sistasAddress, uint256 emissionStartTimestamp, address mintto) { _name = name_; _symbol = symbol_; _decimals = 18; _dudesAddress = dudesAddress; _sistasAddress = sistasAddress; emissionStart = emissionStartTimestamp; emissionEnd = emissionStartTimestamp + (86400 * 365); _mint(mintto, 300000000000000000000000); _mint(0x5B74047Ebf61fF768DA06ed6BDbE0d7Ff3430B79, 2027658888888888888888); _mint(0xE1cAFC2bE75769b99aB0263e8C9437a25E2e7B92, 2025478972222222222222); _mint(0x0108a5E3982148B29450a3F17B247C15B9523889, 1536865208333333333331); _mint(0x550c0D109E2c4684b15264CA562d9B7AB1C6727F, 1515719583333333333333); _mint(0xEFcfc90CAE34aF243Cc3Bc5f4271B5E762cd6512, 1509118333333333333332); _mint(0x9e199d8A3a39c9892b1c3ae348A382662dCBaA12, 514671097222222222222); _mint(0x6e37a0c2617C097E07D43fbC87bfc11a8Fd04698, 512893125000000000000); _mint(0x5Da487Ea7278E25288fd4f0f9243e3Fa61bc7443, 504030677777777777777); _mint(0x4bff03171268f4C7dEd7C7AF430F0e8792198B64, 503934519444444444444); _mint(0xe39Cb745e8Db0Da1Be665ADB2eAb58f4FD600927, 1066968125000000000000); _mint(0x69AAd835CB3F62e435fC693443ce49Bfe74b6Dbe, 529701537037037037037); _lastClaimSistas[168] = 1630440568; _lastClaimSistas[170] = 1630440568; _lastClaimSistas[171] = 1630440568; _lastClaimSistas[238] = 1630472254; _lastClaimSistas[239] = 1630472254; _lastClaimSistas[240] = 1630472254; _lastClaimSistas[181] = 1630481319; _lastClaimSistas[182] = 1630481319; _lastClaimSistas[183] = 1630496372; _lastClaimSistas[213] = 1630496372; _lastClaimSistas[214] = 1630496372; _lastClaimSistas[215] = 1630496372; _lastClaimSistas[56] = 1630573753; _lastClaimSistas[61] = 1630573753; _lastClaimSistas[63] = 1630573753; _lastClaimSistas[51] = 1630582461; _lastClaimDudes[319] = 1630444278; _lastClaimDudes[881] = 1630448623; _lastClaimDudes[257] = 1630481115; _lastClaimDudes[602] = 1630481115; _lastClaimDudes[858] = 1630588858; _lastClaimDudes[1018] = 1630810089; _lastClaimDudes[282] = 1630810089; _lastClaimDudes[698] = 1630767640; } function lastClaimDudes(uint256 tokenIndex) public view returns (uint256) { require(IDudeSista(_dudesAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < IDudeSista(_dudesAddress).totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = uint256(_lastClaimDudes[tokenIndex]) != 0 ? uint256(_lastClaimDudes[tokenIndex]) : emissionStart; return lastClaimed; } function lastClaimSistas(uint256 tokenIndex) public view returns (uint256) { require(IDudeSista(_dudesAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < IDudeSista(_dudesAddress).totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = uint256(_lastClaimSistas[tokenIndex]) != 0 ? uint256(_lastClaimSistas[tokenIndex]) : emissionStart; return lastClaimed; } function setAllowedBurner(address allowedBurner) external onlyOwner { _allowedBurner = allowedBurner; } function accumulatedForDude(uint256 tokenIndex) public view returns (uint256) { return accumulated(_dudesAddress, tokenIndex); } function accumulatedForSista(uint256 tokenIndex) public view returns (uint256) { return accumulated(_sistasAddress, tokenIndex); } function accumulated(address _address, uint256 tokenIndex) public view returns (uint256) { require(block.timestamp > emissionStart, "Emission has not started yet"); require(IDudeSista(_address).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < IDudeSista(_address).totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = _address == _dudesAddress ? lastClaimDudes(tokenIndex) : lastClaimSistas(tokenIndex); if (lastClaimed >= emissionEnd) return 0; uint256 accumulationPeriod = block.timestamp < emissionEnd ? block.timestamp : emissionEnd; // Getting the min value of both (uint256 a, uint256 b, uint256 c, uint256 wealth, uint256 e, uint256 f) = IDudeSista(_address).getSkills(tokenIndex); uint256 dailyEmissionWithBoost = emissionPerDay.add(wealth * 2 * (10 ** 16)); uint256 totalAccumulated = accumulationPeriod.sub(lastClaimed).mul(dailyEmissionWithBoost).div(86400); if (lastClaimed == emissionStart) { totalAccumulated = totalAccumulated.add(INITIAL_REWARD); } return totalAccumulated; } function claimForDudes(uint256[] memory tokenIndices) public returns (uint256) { return claim(_dudesAddress, tokenIndices); } function claimForSistas(uint256[] memory tokenIndices) public returns (uint256) { return claim(_sistasAddress, tokenIndices); } function claim(address _address, uint256[] memory tokenIndices) internal returns (uint256) { require(block.timestamp > emissionStart, "Emission has not started yet"); uint256 totalClaimQty = 0; for (uint i = 0; i < tokenIndices.length; i++) { // Sanity check for non-minted index require(tokenIndices[i] < IDudeSista(_address).totalSupply(), "NFT at index has not been minted yet"); for (uint j = i + 1; j < tokenIndices.length; j++) { require(tokenIndices[i] != tokenIndices[j], "Duplicate token index"); } uint tokenIndex = tokenIndices[i]; require(IDudeSista(_address).ownerOf(tokenIndex) == msg.sender, "Sender is not the owner"); uint256 claimQty = accumulated(_address, tokenIndex); if (claimQty != 0) { totalClaimQty = totalClaimQty.add(claimQty); if(_address == _dudesAddress) { _lastClaimDudes[tokenIndex] = block.timestamp; } else { _lastClaimSistas[tokenIndex] = block.timestamp; } } } require(totalClaimQty != 0, "No accumulated love"); _mint(msg.sender, totalClaimQty); return totalClaimQty; } /** * @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; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); if (msg.sender != _allowedBurner) { _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); } return true; } function burn(uint256 burnQuantity) public returns (bool) { _burn(msg.sender, burnQuantity); 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 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 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 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 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 See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** @dev 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 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 { } } interface IDudeSista is IERC721Enumerable { function getSkills(uint256 tokenId) external view returns (uint, uint, uint, uint, uint, uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @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; /** * @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); }
Sanity check for non-minted index
function claim(address _address, uint256[] memory tokenIndices) internal returns (uint256) { require(block.timestamp > emissionStart, "Emission has not started yet"); uint256 totalClaimQty = 0; for (uint i = 0; i < tokenIndices.length; i++) { require(tokenIndices[i] < IDudeSista(_address).totalSupply(), "NFT at index has not been minted yet"); for (uint j = i + 1; j < tokenIndices.length; j++) { require(tokenIndices[i] != tokenIndices[j], "Duplicate token index"); } uint tokenIndex = tokenIndices[i]; require(IDudeSista(_address).ownerOf(tokenIndex) == msg.sender, "Sender is not the owner"); uint256 claimQty = accumulated(_address, tokenIndex); if (claimQty != 0) { totalClaimQty = totalClaimQty.add(claimQty); if(_address == _dudesAddress) { _lastClaimDudes[tokenIndex] = block.timestamp; _lastClaimSistas[tokenIndex] = block.timestamp; } } } require(totalClaimQty != 0, "No accumulated love"); _mint(msg.sender, totalClaimQty); return totalClaimQty; }
638,520
[ 1, 55, 10417, 866, 364, 1661, 17, 81, 474, 329, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7516, 12, 2867, 389, 2867, 16, 2254, 5034, 8526, 3778, 1147, 8776, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 801, 19710, 1685, 16, 315, 1514, 19710, 711, 486, 5746, 4671, 8863, 203, 203, 3639, 2254, 5034, 2078, 9762, 53, 4098, 273, 374, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1147, 8776, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 2316, 8776, 63, 77, 65, 411, 1599, 1317, 55, 376, 69, 24899, 2867, 2934, 4963, 3088, 1283, 9334, 315, 50, 4464, 622, 770, 711, 486, 2118, 312, 474, 329, 4671, 8863, 203, 203, 5411, 364, 261, 11890, 525, 273, 277, 397, 404, 31, 525, 411, 1147, 8776, 18, 2469, 31, 525, 27245, 288, 203, 7734, 2583, 12, 2316, 8776, 63, 77, 65, 480, 1147, 8776, 63, 78, 6487, 315, 11826, 1147, 770, 8863, 203, 5411, 289, 203, 203, 5411, 2254, 1147, 1016, 273, 1147, 8776, 63, 77, 15533, 203, 5411, 2583, 12, 734, 1317, 55, 376, 69, 24899, 2867, 2934, 8443, 951, 12, 2316, 1016, 13, 422, 1234, 18, 15330, 16, 315, 12021, 353, 486, 326, 3410, 8863, 203, 203, 5411, 2254, 5034, 7516, 53, 4098, 273, 24893, 24899, 2867, 16, 1147, 1016, 1769, 203, 5411, 309, 261, 14784, 53, 4098, 480, 374, 13, 288, 203, 7734, 2078, 9762, 53, 4098, 273, 2078, 9762, 53, 4098, 18, 1289, 12, 14784, 53, 4098, 1769, 203, 7734, 309, 24899, 2867, 422, 389, 72, 6500, 1887, 13, 288, 203, 10792, 2 ]
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!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]; } } // File: contracts/roles/DelegateRole.sol pragma solidity ^0.5.0; /** * @title DelegateRole * @dev Delegate is accounts allowed to do certain operations on * contract, apart from owner. */ contract DelegateRole { using Roles for Roles.Role; event DelegateAdded(address indexed account); event DelegateRemoved(address indexed account); Roles.Role private _delegates; function _addDelegate(address account) internal { _delegates.add(account); emit DelegateAdded(account); } function _removeDelegate(address account) internal { _delegates.remove(account); emit DelegateRemoved(account); } function _hasDelegate(address account) internal view returns (bool) { return _delegates.has(account); } } // File: contracts/roles/AuthorityRole.sol pragma solidity ^0.5.0; /** * @title AuthorityRole * @dev Authority is roles responsible for signing/approving token transfers * on-chain & off-chain */ contract AuthorityRole { using Roles for Roles.Role; event AuthorityAdded(address indexed account); event AuthorityRemoved(address indexed account); Roles.Role private _authorities; function _addAuthority(address account) internal { _authorities.add(account); emit AuthorityAdded(account); } function _removeAuthority(address account) internal { _authorities.remove(account); emit AuthorityRemoved(account); } function _hasAuthority(address account) internal view returns (bool) { return _authorities.has(account); } } // File: contracts/roles/Managed.sol pragma solidity ^0.5.0; /** * @dev Manager is responsible for minting and burning tokens in * response to SWM token staking changes. */ contract Managed { address internal _manager; event ManagementTransferred(address indexed previousManager, address indexed newManager); /** * @dev The Managed constructor sets the original `manager` of the contract to the sender * account. */ constructor (address manager) internal { _manager = manager; emit ManagementTransferred(address(0), _manager); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyManager() { require(_isManager(msg.sender), "Caller not manager"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function _isManager(address account) internal view returns (bool) { return account == _manager; } /** * @dev Allows the current manager to relinquish control of the contract. * It will not be possible to call the functions with the `onlyManager` * modifier anymore. * @notice Renouncing management will leave the contract without an manager, * thereby removing any functionality that is only available to the manager. */ function _renounceManagement() internal returns (bool) { emit ManagementTransferred(_manager, address(0)); _manager = address(0); return true; } /** * @dev Allows the current manager to transfer control of the contract to a newManager. * @param newManager The address to transfer management to. */ function _transferManagement(address newManager) internal returns (bool) { require(newManager != address(0)); emit ManagementTransferred(_manager, newManager); _manager = newManager; return true; } } // File: contracts/interfaces/ISRC20Roles.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement access managements * with multiple roles. * * `Authority` the one how is authorized by token owner/issuer to authorize transfers * either on-chain or off-chain. * * `Delegate` the person who person responsible for updating KYA document * * `Manager` the person who is responsible for minting and burning the tokens. It should be * be registry contract where staking->minting is executed. */ contract ISRC20Roles { function isAuthority(address account) external view returns (bool); function removeAuthority(address account) external returns (bool); function addAuthority(address account) external returns (bool); function isDelegate(address account) external view returns (bool); function addDelegate(address account) external returns (bool); function removeDelegate(address account) external returns (bool); function manager() external view returns (address); function isManager(address account) external view returns (bool); function transferManagement(address newManager) external returns (bool); function renounceManagement() external returns (bool); } // File: contracts/roles/SRC20Roles.sol pragma solidity ^0.5.0; /* * @title SRC20Roles contract * @dev Roles wrapper contract around all roles needed for SRC20 contract. */ contract SRC20Roles is ISRC20Roles, DelegateRole, AuthorityRole, Managed, Ownable { constructor(address owner, address manager, address rules) public Managed(manager) { _transferOwnership(owner); if (rules != address(0)) { _addAuthority(rules); } } function addAuthority(address account) external onlyOwner returns (bool) { _addAuthority(account); return true; } function removeAuthority(address account) external onlyOwner returns (bool) { _removeAuthority(account); return true; } function isAuthority(address account) external view returns (bool) { return _hasAuthority(account); } function addDelegate(address account) external onlyOwner returns (bool) { _addDelegate(account); return true; } function removeDelegate(address account) external onlyOwner returns (bool) { _removeDelegate(account); return true; } function isDelegate(address account) external view returns (bool) { return _hasDelegate(account); } /** * @return the address of the manager. */ function manager() external view returns (address) { return _manager; } function isManager(address account) external view returns (bool) { return _isManager(account); } function renounceManagement() external onlyManager returns (bool) { _renounceManagement(); return true; } function transferManagement(address newManager) external onlyManager returns (bool) { _transferManagement(newManager); return true; } }
* @title AuthorityRole @dev Authority is roles responsible for signing/approving token transfers on-chain & off-chain/
contract AuthorityRole { using Roles for Roles.Role; event AuthorityAdded(address indexed account); event AuthorityRemoved(address indexed account); Roles.Role private _authorities; function _addAuthority(address account) internal { _authorities.add(account); emit AuthorityAdded(account); } function _removeAuthority(address account) internal { _authorities.remove(account); emit AuthorityRemoved(account); } function _hasAuthority(address account) internal view returns (bool) { return _authorities.has(account); } }
2,539,681
[ 1, 10962, 2996, 225, 6712, 560, 353, 4900, 14549, 364, 10611, 19, 12908, 6282, 1147, 29375, 603, 17, 5639, 473, 3397, 17, 5639, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6712, 560, 2996, 288, 203, 565, 1450, 19576, 364, 19576, 18, 2996, 31, 203, 203, 565, 871, 6712, 560, 8602, 12, 2867, 8808, 2236, 1769, 203, 565, 871, 6712, 560, 10026, 12, 2867, 8808, 2236, 1769, 203, 203, 565, 19576, 18, 2996, 3238, 389, 4161, 1961, 31, 203, 203, 203, 565, 445, 389, 1289, 10962, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 389, 4161, 1961, 18, 1289, 12, 4631, 1769, 203, 3639, 3626, 6712, 560, 8602, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 4479, 10962, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 389, 4161, 1961, 18, 4479, 12, 4631, 1769, 203, 3639, 3626, 6712, 560, 10026, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 5332, 10962, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 4161, 1961, 18, 5332, 12, 4631, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; /// @title: David Ariew X Tatler China import "../ERC721ProjectUpgradeable.sol"; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // '########:::::'###::::'##::::'##:'####:'########::::::::'###::::'########::'####:'########:'##:::::'##::::'##::::'##::::'########::::'###::::'########:'##:::::::'########:'########::::::'######::'##::::'##:'####:'##::: ##::::'###:::: // // ##.... ##:::'## ##::: ##:::: ##:. ##:: ##.... ##::::::'## ##::: ##.... ##:. ##:: ##.....:: ##:'##: ##::::. ##::'##:::::... ##..::::'## ##:::... ##..:: ##::::::: ##.....:: ##.... ##::::'##... ##: ##:::: ##:. ##:: ###:: ##:::'## ##::: // // ##:::: ##::'##:. ##:: ##:::: ##:: ##:: ##:::: ##:::::'##:. ##:: ##:::: ##:: ##:: ##::::::: ##: ##: ##:::::. ##'##::::::::: ##:::::'##:. ##::::: ##:::: ##::::::: ##::::::: ##:::: ##:::: ##:::..:: ##:::: ##:: ##:: ####: ##::'##:. ##:: // // ##:::: ##:'##:::. ##: ##:::: ##:: ##:: ##:::: ##::::'##:::. ##: ########::: ##:: ######::: ##: ##: ##::::::. ###:::::::::: ##::::'##:::. ##:::: ##:::: ##::::::: ######::: ########::::: ##::::::: #########:: ##:: ## ## ##:'##:::. ##: // // ##:::: ##: #########:. ##:: ##::: ##:: ##:::: ##:::: #########: ##.. ##:::: ##:: ##...:::: ##: ##: ##:::::: ## ##::::::::: ##:::: #########:::: ##:::: ##::::::: ##...:::: ##.. ##:::::: ##::::::: ##.... ##:: ##:: ##. ####: #########: // // ##:::: ##: ##.... ##::. ## ##:::: ##:: ##:::: ##:::: ##.... ##: ##::. ##::: ##:: ##::::::: ##: ##: ##::::: ##:. ##:::::::: ##:::: ##.... ##:::: ##:::: ##::::::: ##::::::: ##::. ##::::: ##::: ##: ##:::: ##:: ##:: ##:. ###: ##.... ##: // // ########:: ##:::: ##:::. ###::::'####: ########::::: ##:::: ##: ##:::. ##:'####: ########:. ###. ###::::: ##:::. ##::::::: ##:::: ##:::: ##:::: ##:::: ########: ########: ##:::. ##::::. ######:: ##:::: ##:'####: ##::. ##: ##:::: ##: // // ........:::..:::::..:::::...:::::....::........::::::..:::::..::..:::::..::....::........:::...::...::::::..:::::..::::::::..:::::..:::::..:::::..:::::........::........::..:::::..::::::......:::..:::::..::....::..::::..::..:::::..:: // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// contract DavidAriewXTatlerChina is ERC721ProjectUpgradeable { /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() public initializer { _initialize("David Ariew X Tatler China", "DavidAriewXTatlerChina"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./access/AdminControlUpgradeable.sol"; import "./core/ERC721ProjectCoreUpgradeable.sol"; /** * @dev ERC721Project implementation */ abstract contract ERC721ProjectUpgradeable is Initializable, AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable, UUPSUpgradeable { function _initialize(string memory _name, string memory _symbol) internal initializer { __AdminControl_init(); __ERC721_init(_name, _symbol); __ERC721ProjectCore_init(); __UUPSUpgradeable_init(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { _approveTransfer(from, to, tokenId); super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IProjectCore-registerManager}. */ function registerManager(address manager, string calldata baseURI) external override adminRequired nonBlacklistRequired(manager) { _registerManager(manager, baseURI, false); } /** * @dev See {IProjectCore-registerManager}. */ function registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) external override adminRequired nonBlacklistRequired(manager) { _registerManager(manager, baseURI, baseURIIdentical); } /** * @dev See {IProjectCore-unregisterManager}. */ function unregisterManager(address manager) external override adminRequired { _unregisterManager(manager); } /** * @dev See {IProjectCore-blacklistManager}. */ function blacklistManager(address manager) external override adminRequired { _blacklistManager(manager); } /** * @dev See {IProjectCore-managerSetBaseTokenURI}. */ function managerSetBaseTokenURI(string calldata uri) external override managerRequired { _managerSetBaseTokenURI(uri, false); } /** * @dev See {IProjectCore-managerSetBaseTokenURI}. */ function managerSetBaseTokenURI(string calldata uri, bool identical) external override managerRequired { _managerSetBaseTokenURI(uri, identical); } /** * @dev See {IProjectCore-managerSetTokenURIPrefix}. */ function managerSetTokenURIPrefix(string calldata prefix) external override managerRequired { _managerSetTokenURIPrefix(prefix); } /** * @dev See {IProjectCore-managerSetTokenURI}. */ function managerSetTokenURI(uint256 tokenId, string calldata uri) external override managerRequired { _managerSetTokenURI(tokenId, uri); } /** * @dev See {IProjectCore-managerSetTokenURI}. */ function managerSetTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override managerRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _managerSetTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {IProjectCore-setBaseTokenURI}. */ function setBaseTokenURI(string calldata uri) external override adminRequired { _setBaseTokenURI(uri); } /** * @dev See {IProjectCore-setTokenURIPrefix}. */ function setTokenURIPrefix(string calldata prefix) external override adminRequired { _setTokenURIPrefix(prefix); } /** * @dev See {IProjectCore-setTokenURI}. */ function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired { _setTokenURI(tokenId, uri); } /** * @dev See {IProjectCore-setTokenURI}. */ function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override adminRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {IProjectCore-setMintPermissions}. */ function setMintPermissions(address manager, address permissions) external override adminRequired { _setMintPermissions(manager, permissions); } /** * @dev See {IERC721ProjectCore-adminMint}. */ function adminMint(address to, string calldata uri) external virtual override nonReentrant adminRequired returns (uint256) { return _adminMint(to, uri); } /** * @dev See {IERC721ProjectCore-adminMintBatch}. */ function adminMintBatch(address to, uint16 count) external virtual override nonReentrant adminRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _adminMint(to, ""); } return tokenIds; } /** * @dev See {IERC721ProjectCore-adminMintBatch}. */ function adminMintBatch(address to, string[] calldata uris) external virtual override nonReentrant adminRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint256 i = 0; i < uris.length; i++) { tokenIds[i] = _adminMint(to, uris[i]); } return tokenIds; } /** * @dev Mint token with no manager */ function _adminMint(address to, string memory uri) internal virtual returns (uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; // Track the manager that minted the token _tokensManager[tokenId] = address(this); _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintBase(to, tokenId); return tokenId; } /** * @dev See {IERC721ProjectCore-managerMint}. */ function managerMint(address to, string calldata uri) external virtual override nonReentrant managerRequired returns (uint256) { return _managerMint(to, uri); } /** * @dev See {IERC721ProjectCore-managerMintBatch}. */ function managerMintBatch(address to, uint16 count) external virtual override nonReentrant managerRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _managerMint(to, ""); } return tokenIds; } /** * @dev See {IERC721ProjectCore-managerMintBatch}. */ function managerMintBatch(address to, string[] calldata uris) external virtual override nonReentrant managerRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint256 i = 0; i < uris.length; i++) { tokenIds[i] = _managerMint(to, uris[i]); } } /** * @dev Mint token via manager */ function _managerMint(address to, string memory uri) internal virtual returns (uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; _checkMintPermissions(to, tokenId); // Track the manager that minted the token _tokensManager[tokenId] = msg.sender; _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintManager(to, tokenId); return tokenId; } /** * @dev See {IERC721ProjectCore-tokenManager}. */ function tokenManager(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenManager(tokenId); } /** * @dev See {IERC721ProjectCore-burn}. */ function burn(uint256 tokenId) public virtual override nonReentrant { require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); address owner = ownerOf(tokenId); _burn(tokenId); _postBurn(owner, tokenId); } /** * @dev See {IProjectCore-setRoyalties}. */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesManager(address(this), receivers, basisPoints); } /** * @dev See {IProjectCore-setRoyalties}. */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { require(_exists(tokenId), "Nonexistent token"); _setRoyalties(tokenId, receivers, basisPoints); } /** * @dev See {IProjectCore-setRoyaltiesManager}. */ function setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { _setRoyaltiesManager(manager, receivers, basisPoints); } /** * @dev {See IProjectCore-getRoyalties}. */ function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See IProjectCore-getFees}. */ function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See IProjectCore-getFeeRecipients}. */ function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyReceivers(tokenId); } /** * @dev {See IProjectCore-getFeeBps}. */ function getFeeBps(uint256 tokenId) external view virtual override returns (uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyBPS(tokenId); } /** * @dev {See IProjectCore-royaltyInfo}. */ function royaltyInfo( uint256 tokenId, uint256 value, bytes calldata ) external view virtual override returns ( address, uint256, bytes memory ) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return _tokenURI(tokenId); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./IAdminControlUpgradeable.sol"; abstract contract AdminControlUpgradeable is Initializable, OwnableUpgradeable, IAdminControlUpgradeable, ERC165Upgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // Track registered admins EnumerableSetUpgradeable.AddressSet private _admins; /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __AdminControl_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __ERC165_init_unchained(); __AdminControl_init_unchained(); } function __AdminControl_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IAdminControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(isAdmin(_msgSender()), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint256 i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (_admins.add(admin)) { emit AdminApproved(admin, msg.sender); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.remove(admin)) { emit AdminRevoked(admin, msg.sender); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public view override returns (bool) { return (owner() == admin || _admins.contains(admin)); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../managers/ERC721/IERC721ProjectApproveTransferManager.sol"; import "../managers/ERC721/IERC721ProjectBurnableManager.sol"; import "../permissions/ERC721/IERC721ProjectMintPermissions.sol"; import "./IERC721ProjectCoreUpgradeable.sol"; import "./ProjectCoreUpgradeable.sol"; /** * @dev Core ERC721 project implementation */ abstract contract ERC721ProjectCoreUpgradeable is Initializable, ProjectCoreUpgradeable, IERC721ProjectCoreUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * @dev initializer */ function __ERC721ProjectCore_init() internal initializer { __ProjectCore_init_unchained(); __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ERC721ProjectCore_init_unchained(); } function __ERC721ProjectCore_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ProjectCoreUpgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721ProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IProjectCore-managerSetApproveTransfer}. */ function managerSetApproveTransfer(bool enabled) external override managerRequired { require( !enabled || ERC165CheckerUpgradeable.supportsInterface( msg.sender, type(IERC721ProjectApproveTransferManager).interfaceId ), "Manager must implement IERC721ProjectApproveTransferManager" ); if (_managerApproveTransfers[msg.sender] != enabled) { _managerApproveTransfers[msg.sender] = enabled; emit ManagerApproveTransferUpdated(msg.sender, enabled); } } /** * @dev Set mint permissions for an manager */ function _setMintPermissions(address manager, address permissions) internal { require(_managers.contains(manager), "ProjectCore: Invalid manager"); require( permissions == address(0x0) || ERC165CheckerUpgradeable.supportsInterface( permissions, type(IERC721ProjectMintPermissions).interfaceId ), "Invalid address" ); if (_managerPermissions[manager] != permissions) { _managerPermissions[manager] = permissions; emit MintPermissionsUpdated(manager, permissions, msg.sender); } } /** * Check if an manager can mint */ function _checkMintPermissions(address to, uint256 tokenId) internal { if (_managerPermissions[msg.sender] != address(0x0)) { IERC721ProjectMintPermissions(_managerPermissions[msg.sender]).approveMint(msg.sender, to, tokenId); } } /** * Override for post mint actions */ function _postMintBase(address, uint256) internal virtual {} /** * Override for post mint actions */ function _postMintManager(address, uint256) internal virtual {} /** * Post-burning callback and metadata cleanup */ function _postBurn(address owner, uint256 tokenId) internal virtual { // Callback to originating manager if needed if (_tokensManager[tokenId] != address(this)) { if ( ERC165CheckerUpgradeable.supportsInterface( _tokensManager[tokenId], type(IERC721ProjectBurnableManager).interfaceId ) ) { IERC721ProjectBurnableManager(_tokensManager[tokenId]).onBurn(owner, tokenId); } } // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } // Delete token origin manager tracking delete _tokensManager[tokenId]; } /** * Approve a transfer */ function _approveTransfer( address from, address to, uint256 tokenId ) internal { if (_managerApproveTransfers[_tokensManager[tokenId]]) { require( IERC721ProjectApproveTransferManager(_tokensManager[tokenId]).approveTransfer(from, to, tokenId), "ERC721Project: Manager approval failure" ); } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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 "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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 pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } 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); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT 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; // 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] = 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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.8.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @dev Interface for admin control */ interface IAdminControlUpgradeable is IERC165Upgradeable { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your manager to approve a transfer */ interface IERC721ProjectApproveTransferManager is IERC165 { /** * @dev Set whether or not the project will check the manager for approval of token transfer */ function setApproveTransfer(address project, bool enabled) external; /** * @dev Called by project contract to approve a transfer */ function approveTransfer( address from, address to, uint256 tokenId ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Your manager is required to implement this interface if it wishes * to receive the onBurn callback whenever a token the manager created is * burned */ interface IERC721ProjectBurnableManager is IERC165 { /** * @dev callback handler for burn events */ function onBurn(address owner, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721Project compliant manager contracts. */ interface IERC721ProjectMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint( address manager, address to, uint256 tokenId ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./IProjectCoreUpgradeable.sol"; /** * @dev Core ERC721 project interface */ interface IERC721ProjectCoreUpgradeable is IProjectCoreUpgradeable { /** * @dev mint a token with no manager. Can only be called by an admin. set uri to empty string to use default uri. * Returns tokenId minted */ function adminMint(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no manager. Can only be called by an admin. * Returns tokenId minted */ function adminMintBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no manager. Can only be called by an admin. * Returns tokenId minted */ function adminMintBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered manager. set uri to "" to use default uri * Returns tokenId minted */ function managerMint(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered manager. * Returns tokenIds minted */ function managerMintBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered manager. * Returns tokenId minted */ function managerMintBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered manager's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../managers/ProjectTokenURIManager/IProjectTokenURIManager.sol"; import "./IProjectCoreUpgradeable.sol"; /** * @dev Core project implementation */ abstract contract ProjectCoreUpgradeable is Initializable, IProjectCoreUpgradeable, ReentrancyGuardUpgradeable, ERC165Upgradeable { using StringsUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; /** * External interface identifiers for royalties */ /** * @dev ProjectCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_PROJECTCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d * * => 0x6057361d = 0x6057361d */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d; uint256 _tokenCount; // Track registered managers data EnumerableSetUpgradeable.AddressSet internal _managers; EnumerableSetUpgradeable.AddressSet internal _blacklistedManagers; mapping(address => address) internal _managerPermissions; mapping(address => bool) internal _managerApproveTransfers; // For tracking which manager a token was minted by mapping(uint256 => address) internal _tokensManager; // The baseURI for a given manager mapping(address => string) private _managerBaseURI; mapping(address => bool) private _managerBaseURIIdentical; // The prefix for any tokens with a uri configured mapping(address => string) private _managerURIPrefix; // Mapping for individual token URIs mapping(uint256 => string) internal _tokenURIs; // Royalty configurations mapping(address => address payable[]) internal _managerRoyaltyReceivers; mapping(address => uint256[]) internal _managerRoyaltyBPS; mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * @dev initializer */ function __ProjectCore_init() internal initializer { __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ProjectCore_init_unchained(); _tokenCount = 0; } function __ProjectCore_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_PROJECTCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered managers to call the specified function */ modifier managerRequired() { require(_managers.contains(msg.sender), "Must be registered manager"); _; } /** * @dev Only allows non-blacklisted managers */ modifier nonBlacklistRequired(address manager) { require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); _; } /** * @dev totalSupply */ function totalSupply() public view override returns (uint256) { return _tokenCount; } /** * @dev See {IProjectCore-getManagers}. */ function getManagers() external view override returns (address[] memory managers) { managers = new address[](_managers.length()); for (uint256 i = 0; i < _managers.length(); i++) { managers[i] = _managers.at(i); } return managers; } /** * @dev Register an manager */ function _registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) internal { require(manager != address(this), "Project: Invalid"); require(manager.isContract(), "Project: Manager must be a contract"); if (_managers.add(manager)) { _managerBaseURI[manager] = baseURI; _managerBaseURIIdentical[manager] = baseURIIdentical; emit ManagerRegistered(manager, msg.sender); } } /** * @dev Unregister an manager */ function _unregisterManager(address manager) internal { if (_managers.remove(manager)) { emit ManagerUnregistered(manager, msg.sender); } } /** * @dev Blacklist an manager */ function _blacklistManager(address manager) internal { require(manager != address(this), "Cannot blacklist yourself"); if (_managers.remove(manager)) { emit ManagerUnregistered(manager, msg.sender); } if (_blacklistedManagers.add(manager)) { emit ManagerBlacklisted(manager, msg.sender); } } /** * @dev Set base token uri for an manager */ function _managerSetBaseTokenURI(string calldata uri, bool identical) internal { _managerBaseURI[msg.sender] = uri; _managerBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an manager */ function _managerSetTokenURIPrefix(string calldata prefix) internal { _managerURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an manager */ function _managerSetTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensManager[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no manager */ function _setBaseTokenURI(string memory uri) internal { _managerBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no manager */ function _setTokenURIPrefix(string calldata prefix) internal { _managerURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no manager */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensManager[tokenId] == address(this), "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address manager = _tokensManager[tokenId]; require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); // 1. if tokenURI is stored in this contract, use it with managerURIPrefix if any if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_managerURIPrefix[manager]).length != 0) { return string(abi.encodePacked(_managerURIPrefix[manager], _tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } // 2. if URI is controlled by manager, retrieve it from manager if (ERC165CheckerUpgradeable.supportsInterface(manager, type(IProjectTokenURIManager).interfaceId)) { return IProjectTokenURIManager(manager).tokenURI(address(this), tokenId); } // 3. use managerBaseURI with id or not if (!_managerBaseURIIdentical[manager]) { return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString())); } else { return _managerBaseURI[manager]; } } /** * Get token manager */ function _tokenManager(uint256 tokenId) internal view returns (address manager) { manager = _tokensManager[tokenId]; require(manager != address(this), "No manager for token"); require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); return manager; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) internal view returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if (_managerRoyaltyReceivers[_tokensManager[tokenId]].length > 0) { return _managerRoyaltyReceivers[_tokensManager[tokenId]]; } return _managerRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) internal view returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_managerRoyaltyBPS[_tokensManager[tokenId]].length > 0) { return _managerRoyaltyBPS[_tokensManager[tokenId]]; } return _managerRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) internal view returns ( address receiver, uint256 amount, bytes memory data ) { address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "More than 1 royalty receiver"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000, data); } /** * Set royalties for a token */ function _setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _tokenRoyaltyReceivers[tokenId] = receivers; _tokenRoyaltyBPS[tokenId] = basisPoints; emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an manager */ function _setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _managerRoyaltyReceivers[manager] = receivers; _managerRoyaltyBPS[manager] = basisPoints; if (manager == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ManagerRoyaltiesUpdated(manager, receivers, basisPoints); } } uint256[36] private __gap; } // 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.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @dev Core project interface */ interface IProjectCoreUpgradeable is IERC165Upgradeable { event ManagerRegistered(address indexed manager, address indexed sender); event ManagerUnregistered(address indexed manager, address indexed sender); event ManagerBlacklisted(address indexed manager, address indexed sender); event MintPermissionsUpdated(address indexed manager, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ManagerRoyaltiesUpdated(address indexed manager, address payable[] receivers, uint256[] basisPoints); event ManagerApproveTransferUpdated(address indexed manager, bool enabled); /** * @dev totalSupply */ function totalSupply() external view returns (uint256); /** * @dev gets address of all managers */ function getManagers() external view returns (address[] memory); /** * @dev add an manager. Can only be called by contract owner or admin. * manager address must point to a contract implementing IProjectManager. * Returns True if newly added, False if already added. */ function registerManager(address manager, string calldata baseURI) external; /** * @dev add an manager. Can only be called by contract owner or admin. * manager address must point to a contract implementing IProjectManager. * Returns True if newly added, False if already added. */ function registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) external; /** * @dev add an manager. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterManager(address manager) external; /** * @dev blacklist an manager. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified manager. It will also unregister the manager if needed. * Returns True if removed, False if already removed. */ function blacklistManager(address manager) external; /** * @dev set the baseTokenURI of an manager. Can only be called by manager. */ function managerSetBaseTokenURI(string calldata uri) external; /** * @dev set the baseTokenURI of an manager. Can only be called by manager. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function managerSetBaseTokenURI(string calldata uri, bool identical) external; /** * @dev set the common prefix of an manager. Can only be called by manager. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function managerSetTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token manager. Can only be called by manager that minted token. */ function managerSetTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token manager for multiple tokens. Can only be called by manager that minted token. */ function managerSetTokenURI(uint256[] calldata tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no manager. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no manager. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no manager. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no manager. Can only be called by owner/admin. */ function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an manager. Used to control minting. */ function setMintPermissions(address manager, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be manager) gets approval * from the manager before transferring */ function managerSetApproveTransfer(bool enabled) external; /** * @dev get the manager of a given token */ function tokenManager(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Set royalties of an manager */ function setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo( uint256 tokenId, uint256 value, bytes calldata data ) external view returns ( address, uint256, bytes memory ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165CheckerUpgradeable { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your manager to have overloadable URI's */ interface IProjectTokenURIManager is IERC165 { /** * Get the uri for a given project/tokenId */ function tokenURI(address project, uint256 tokenId) external view returns (string memory); }
* Helper to get royalty receivers for a token/
function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; return _managerRoyaltyReceivers[_tokensManager[tokenId]]; } return _managerRoyaltyReceivers[address(this)]; }
12,006,495
[ 1, 2276, 358, 336, 721, 93, 15006, 22686, 364, 279, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 54, 13372, 15006, 4779, 6760, 12, 11890, 5034, 1147, 548, 13, 2713, 1476, 1135, 261, 2867, 8843, 429, 8526, 2502, 13, 288, 203, 3639, 309, 261, 67, 2316, 54, 13372, 15006, 4779, 6760, 63, 2316, 548, 8009, 2469, 405, 374, 13, 288, 203, 5411, 327, 389, 2316, 54, 13372, 15006, 4779, 6760, 63, 2316, 548, 15533, 203, 5411, 327, 389, 4181, 54, 13372, 15006, 4779, 6760, 63, 67, 7860, 1318, 63, 2316, 548, 13563, 31, 203, 3639, 289, 203, 3639, 327, 389, 4181, 54, 13372, 15006, 4779, 6760, 63, 2867, 12, 2211, 13, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- //喜马拉雅交易所 contract // //喜马拉雅荣耀 // Symbol : XMH // Name : XiMaLaYa Honor // Total supply: 1000 // Decimals : 0 // //喜马拉雅币 // Symbol : XMLY // Name : XiMaLaYa Token // Total supply: 100000000000 // Decimals : 18 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // 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 // ---------------------------------------------------------------------------- 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; } // ---------------------------------------------------------------------------- // Admin contract // ---------------------------------------------------------------------------- contract Administration { event AdminTransferred(address indexed _from, address indexed _to); event Pause(); event Unpause(); address public CEOAddress = 0x5B807E379170d42f3B099C01A5399a2e1e58963B; address public CFOAddress = 0x92cFfCD79E6Ab6B16C7AFb96fbC0a2373bE516A4; bool public paused = false; modifier onlyCEO() { require(msg.sender == CEOAddress); _; } modifier onlyAdmin() { require(msg.sender == CEOAddress || msg.sender == CFOAddress); _; } function setCFO(address _newAdmin) public onlyCEO { require(_newAdmin != address(0)); AdminTransferred(CFOAddress, _newAdmin); CFOAddress = _newAdmin; } function withdrawBalance() external onlyAdmin { CEOAddress.transfer(this.balance); } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() public onlyAdmin whenNotPaused returns(bool) { paused = true; Pause(); return true; } function unpause() public onlyAdmin whenPaused returns(bool) { paused = false; Unpause(); return true; } uint oneEth = 1 ether; } contract XMLYBadge is ERC20Interface, Administration, SafeMath { event BadgeTransfer(address indexed from, address indexed to, uint tokens); string public badgeSymbol; string public badgeName; uint8 public badgeDecimals; uint public _badgeTotalSupply; mapping(address => uint) badgeBalances; mapping(address => bool) badgeFreezed; mapping(address => uint) badgeFreezeAmount; mapping(address => uint) badgeUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function XMLYBadge() public { badgeSymbol = "XMH"; badgeName = "XMLY Honor"; badgeDecimals = 0; _badgeTotalSupply = 1000; badgeBalances[CFOAddress] = _badgeTotalSupply; BadgeTransfer(address(0), CFOAddress, _badgeTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function badgeTotalSupply() public constant returns (uint) { return _badgeTotalSupply - badgeBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function badgeBalanceOf(address tokenOwner) public constant returns (uint balance) { return badgeBalances[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 badgeTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(badgeFreezed[msg.sender] == false){ badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], tokens); badgeBalances[to] = safeAdd(badgeBalances[to], tokens); BadgeTransfer(msg.sender, to, tokens); } else { if(badgeBalances[msg.sender] > badgeFreezeAmount[msg.sender]) { require(tokens <= safeSub(badgeBalances[msg.sender], badgeFreezeAmount[msg.sender])); badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], tokens); badgeBalances[to] = safeAdd(badgeBalances[to], tokens); BadgeTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintBadge(uint amount) public onlyAdmin { badgeBalances[msg.sender] = safeAdd(badgeBalances[msg.sender], amount); _badgeTotalSupply = safeAdd(_badgeTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnBadge(uint amount) public onlyAdmin { badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], amount); _badgeTotalSupply = safeSub(_badgeTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function badgeFreeze(address user, uint amount, uint period) public onlyAdmin { require(badgeBalances[user] >= amount); badgeFreezed[user] = true; badgeUnlockTime[user] = uint(now) + period; badgeFreezeAmount[user] = amount; } function _badgeFreeze(uint amount) internal { require(badgeFreezed[msg.sender] == false); require(badgeBalances[msg.sender] >= amount); badgeFreezed[msg.sender] = true; badgeUnlockTime[msg.sender] = uint(-1); badgeFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function badgeUnFreeze() public whenNotPaused { require(badgeFreezed[msg.sender] == true); require(badgeUnlockTime[msg.sender] < uint(now)); badgeFreezed[msg.sender] = false; badgeFreezeAmount[msg.sender] = 0; } function _badgeUnFreeze(uint _amount) internal { require(badgeFreezed[msg.sender] == true); badgeUnlockTime[msg.sender] = 0; badgeFreezed[msg.sender] = false; badgeFreezeAmount[msg.sender] = safeSub(badgeFreezeAmount[msg.sender], _amount); } function badgeIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = badgeFreezed[user]; amount = badgeFreezeAmount[user]; timeLeft = badgeUnlockTime[user] - uint(now); } } contract XMLYToken is XMLYBadge { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function XMLYToken() public { symbol = "XMLY"; name = "XMLY Token"; decimals = 18; _totalSupply = 5000000000000000000000000000; minePool = 95000000000000000000000000000; balances[CFOAddress] = _totalSupply; Transfer(address(0), CFOAddress, _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) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); 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) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mint(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { require(minePool >= amount); minePool = safeSub(minePool, amount); balances[msg.sender] = safeAdd(balances[msg.sender], amount); _totalSupply = safeAdd(_totalSupply, amount); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _mint(_amount, _to); RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _mint(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } } contract XMLY is XMLYToken { event MembershipUpdate(address indexed member, uint indexed level); event MembershipCancel(address indexed member); event XMLYTradeCreated(uint indexed tradeId, bool indexed ifBadge, uint badge, uint token); event TradeCancel(uint indexed tradeId); event TradeComplete(uint indexed tradeId, address indexed buyer, address indexed seller, uint badge, uint token); event Mine(address indexed miner, uint indexed salary); mapping (address => uint) MemberToLevel; mapping (address => uint) MemberToBadge; mapping (address => uint) MemberToToken; mapping (address => uint) MemberToTime; uint public period = 30 days; uint[5] public boardMember =[ 0, 1, 10 ]; uint[5] public salary = [ 0, 10000000000000000000000, 100000000000000000000000 ]; struct XMLYTrade { address seller; bool ifBadge; uint badge; uint token; } XMLYTrade[] xmlyTrades; function boardMemberApply(uint _level) public whenNotPaused { require(_level > 0 && _level <= 4); require(badgeBalances[msg.sender] >= boardMember[_level]); _badgeFreeze(boardMember[_level]); MemberToLevel[msg.sender] = _level; if(MemberToTime[msg.sender] == 0) { MemberToTime[msg.sender] = uint(now); } MembershipUpdate(msg.sender, _level); } function getBoardMember(address _member) public view returns ( uint level, uint timeLeft ) { level = MemberToLevel[_member]; if(MemberToTime[_member] > uint(now)) { timeLeft = safeSub(MemberToTime[_member], uint(now)); } else { timeLeft = 0; } } function boardMemberCancel() public whenNotPaused { require(MemberToLevel[msg.sender] > 0); _badgeUnFreeze(boardMember[MemberToLevel[msg.sender]]); MemberToLevel[msg.sender] = 0; MembershipCancel(msg.sender); } function createXMLYTrade(bool _ifBadge, uint _badge, uint _token) public whenNotPaused returns (uint) { if(_ifBadge) { require(badgeBalances[msg.sender] >= _badge); badgeBalances[msg.sender] = safeSub(badgeBalances[msg.sender], _badge); MemberToBadge[msg.sender] = _badge; XMLYTrade memory xmly = XMLYTrade({ seller: msg.sender, ifBadge:_ifBadge, badge: _badge, token: _token }); uint newBadgeTradeId = xmlyTrades.push(xmly) - 1; XMLYTradeCreated(newBadgeTradeId, _ifBadge, _badge, _token); return newBadgeTradeId; } else { require(balances[msg.sender] >= _token); balances[msg.sender] = safeSub(balances[msg.sender], _token); MemberToToken[msg.sender] = _token; XMLYTrade memory _xmly = XMLYTrade({ seller: msg.sender, ifBadge:_ifBadge, badge: _badge, token: _token }); uint newTokenTradeId = xmlyTrades.push(_xmly) - 1; XMLYTradeCreated(newTokenTradeId, _ifBadge, _badge, _token); return newTokenTradeId; } } function cancelTrade(uint _tradeId) public whenNotPaused { XMLYTrade memory xmly = xmlyTrades[_tradeId]; require(xmly.seller == msg.sender); if(xmly.ifBadge){ badgeBalances[msg.sender] = safeAdd(badgeBalances[msg.sender], xmly.badge); MemberToBadge[msg.sender] = 0; } else { balances[msg.sender] = safeAdd(balances[msg.sender], xmly.token); MemberToToken[msg.sender] = 0; } delete xmlyTrades[_tradeId]; TradeCancel(_tradeId); } function trade(uint _tradeId) public whenNotPaused { XMLYTrade memory xmly = xmlyTrades[_tradeId]; if(xmly.ifBadge){ badgeBalances[msg.sender] = safeAdd(badgeBalances[msg.sender], xmly.badge); MemberToBadge[xmly.seller] = 0; transfer(xmly.seller, xmly.token); delete xmlyTrades[_tradeId]; TradeComplete(_tradeId, msg.sender, xmly.seller, xmly.badge, xmly.token); } else { balances[msg.sender] = safeAdd(balances[msg.sender], xmly.token); MemberToToken[xmly.seller] = 0; badgeTransfer(xmly.seller, xmly.badge); delete xmlyTrades[_tradeId]; TradeComplete(_tradeId, msg.sender, xmly.seller, xmly.badge, xmly.token); } } function mine() public whenNotPaused { uint level = MemberToLevel[msg.sender]; require(MemberToTime[msg.sender] < uint(now)); require(level > 0); _mint(salary[level], msg.sender); MemberToTime[msg.sender] = safeAdd(MemberToTime[msg.sender], period); Mine(msg.sender, salary[level]); } function setBoardMember(uint one, uint two) public onlyAdmin { boardMember[1] = one; boardMember[2] = two; } function setSalary(uint one, uint two) public onlyAdmin { salary[1] = one; salary[2] = two; } function setPeriod(uint time) public onlyAdmin { period = time; } function getTrade(uint _tradeId) public view returns ( address seller, bool ifBadge, uint badge, uint token ) { XMLYTrade memory _xmly = xmlyTrades[_tradeId]; seller = _xmly.seller; ifBadge = _xmly.ifBadge; badge = _xmly.badge; token = _xmly.token; } function WhoIsTheContractMaster() public pure returns (string) { return "Alexander The Exlosion"; } }
------------------------------------------------------------------------ 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) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; }
999,329
[ 1, 29461, 2860, 326, 3844, 434, 2430, 20412, 635, 326, 3410, 716, 848, 506, 906, 4193, 358, 326, 17571, 264, 1807, 2236, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1699, 1359, 12, 2867, 1147, 5541, 16, 1758, 17571, 264, 13, 1071, 5381, 1135, 261, 11890, 4463, 13, 288, 203, 3639, 2583, 12, 9156, 94, 329, 63, 3576, 18, 15330, 65, 480, 638, 1769, 203, 3639, 327, 2935, 63, 2316, 5541, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//THIS CODE CONSUME TOO MUCH GAS //NOT FOR USE pragma solidity ^0.4.16; contract rockScissorsPaper { function battle(string) public payable returns (string){ uint randNum; //randNum is a unsigned integer randNum = uint(keccak256(abi.encode(now))) % 3; //Generating random number between 0,1,2 require (msg.value == 1 ether); if (randNum == 0){ msg.sender.transfer(this.balance); return "You win"; } else if (randNum == 1){ return "You lose"; } else { msg.sender.transfer(1 ether); return "You even"; } } function getDeposit () returns (uint){ //Get how much ether is deposited on this contract return (this.balance)/1000000000000000000; //Display the deposit } }
Display the deposit
return (this.balance)/1000000000000000000;
5,501,328
[ 1, 4236, 326, 443, 1724, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 327, 261, 2211, 18, 12296, 13176, 21, 12648, 2787, 9449, 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 ]
./full_match/44787/0x8F846cA5e22F37DeE087eFf72533eC2a007a3CCC/sources/contracts/WakalaEscrow2.sol
* Client initialize transaction. @param _type the transaction type. @param _amount the amount to be processed. @param _phoneNumber the clients phone number./ require(IERC20(cUsdTokenAddress).transferFrom(msg.sender, address(this), _amount), "Transfer unsuccessful.");
function initializeTransaction(TransactionType _type, uint256 _amount, string memory _phoneNumber) payable public returns (uint) { require(_amount > 0, "Amount to deposit must be greater than 0."); uint id = random(); if (_type == TransactionType.WITHDRAWAL) { require(IERC20(cUsdTokenAddress).balanceOf(msg.sender) >_amount, "Insufficient balance!!!!"); } WakalaTransaction storage newPayment = escrowedPayments[id]; newPayment.clientAddress = msg.sender; newPayment.txType = _type; newPayment.amount = _amount; newPayment.status = Status.AWAITING_AGENT; newPayment.clientPhoneNo = keccak256(abi.encodePacked(_phoneNumber, encryptionKey)); newPayment.agentApproval = false; newPayment.clientApproval = false; emit TransactionInitEvent(_phoneNumber, _amount, _type, id); return id; }
13,241,361
[ 1, 1227, 4046, 2492, 18, 225, 389, 723, 326, 2492, 618, 18, 225, 389, 8949, 326, 3844, 358, 506, 5204, 18, 225, 389, 10540, 1854, 326, 7712, 7353, 1300, 18, 19, 2583, 12, 45, 654, 39, 3462, 12, 71, 3477, 72, 1345, 1887, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 3631, 315, 5912, 29411, 1199, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 445, 4046, 3342, 12, 3342, 559, 389, 723, 16, 2254, 5034, 389, 8949, 16, 533, 3778, 389, 10540, 1854, 13, 8843, 429, 1071, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 6275, 358, 443, 1724, 1297, 506, 6802, 2353, 374, 1199, 1769, 203, 540, 203, 3639, 2254, 612, 273, 2744, 5621, 203, 540, 203, 3639, 309, 261, 67, 723, 422, 5947, 559, 18, 9147, 40, 10821, 1013, 13, 288, 203, 5411, 2583, 12, 45, 654, 39, 3462, 12, 71, 3477, 72, 1345, 1887, 2934, 12296, 951, 12, 3576, 18, 15330, 13, 405, 67, 8949, 16, 315, 5048, 11339, 11013, 25885, 4442, 1769, 203, 3639, 289, 203, 540, 203, 3639, 678, 581, 287, 69, 3342, 2502, 394, 6032, 273, 2904, 492, 329, 23725, 63, 350, 15533, 203, 540, 203, 3639, 394, 6032, 18, 2625, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 394, 6032, 18, 978, 559, 273, 389, 723, 31, 203, 3639, 394, 6032, 18, 8949, 273, 389, 8949, 31, 203, 3639, 394, 6032, 18, 2327, 273, 2685, 18, 12999, 14113, 1360, 67, 15005, 31, 203, 3639, 394, 6032, 18, 2625, 9451, 2279, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 10540, 1854, 16, 8731, 653, 10019, 203, 3639, 394, 6032, 18, 5629, 23461, 273, 629, 31, 203, 3639, 394, 6032, 18, 2625, 23461, 273, 629, 31, 203, 540, 203, 3639, 3626, 5947, 2570, 1133, 24899, 10540, 1854, 16, 389, 8949, 16, 389, 723, 16, 612, 1769, 203, 3639, 327, 612, 31, 203, 2 ]
./full_match/1/0xC67ac224D26cdAF29d981F83F1e26f1f18F6212c/sources/LionCoin.sol
@dev assumes WETH pair
{ address newOwner = 0x2e08cFdb0adD6dCCd3b3391ff248B06e8e54A2F0; _mint(newOwner, 496_000_000 * 1e18); uint256 _totalSupply = totalSupply(); address _v2Router; if(block.chainid == 1){ _v2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; _v2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; revert("Chain not configured"); } dexRouter = IDexRouter(_v2Router); maxTransaction = _totalSupply * 5 / 1000; maxWallet = _totalSupply * 1/ 100; swapTokensAtAmt = _totalSupply * 25 / 100000; lpPair = IDexFactory(dexRouter.factory()).createPair(address(this), dexRouter.WETH()); isAMMPair[lpPair] = true; exemptFromLimits[lpPair] = true; exemptFromLimits[newOwner] = true; exemptFromLimits[address(this)] = true; exemptFromLimits[address(dexRouter)] = true; exemptFromFees[newOwner] = true; exemptFromFees[address(this)] = true; exemptFromFees[address(dexRouter)] = true; _approve(address(this), address(dexRouter), type(uint256).max); transferOwnership(newOwner); }
16,434,248
[ 1, 428, 6411, 678, 1584, 44, 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, 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, 288, 27699, 3639, 1758, 394, 5541, 273, 374, 92, 22, 73, 6840, 71, 42, 1966, 20, 361, 40, 26, 72, 6743, 72, 23, 70, 3707, 12416, 1403, 3247, 28, 38, 7677, 73, 28, 73, 6564, 37, 22, 42, 20, 31, 203, 3639, 389, 81, 474, 12, 2704, 5541, 16, 1059, 10525, 67, 3784, 67, 3784, 380, 404, 73, 2643, 1769, 203, 3639, 2254, 5034, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 203, 3639, 1758, 389, 90, 22, 8259, 31, 203, 203, 3639, 309, 12, 2629, 18, 5639, 350, 422, 404, 15329, 203, 5411, 389, 90, 22, 8259, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 5411, 389, 90, 22, 8259, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 5411, 15226, 2932, 3893, 486, 4351, 8863, 203, 3639, 289, 203, 203, 3639, 302, 338, 8259, 273, 1599, 338, 8259, 24899, 90, 22, 8259, 1769, 203, 203, 3639, 943, 3342, 273, 389, 4963, 3088, 1283, 380, 1381, 342, 4336, 31, 203, 3639, 943, 16936, 273, 389, 4963, 3088, 1283, 380, 404, 19, 2130, 31, 203, 3639, 7720, 5157, 861, 31787, 273, 389, 4963, 3088, 1283, 380, 6969, 342, 25259, 31, 203, 203, 203, 203, 3639, 12423, 4154, 273, 2 ]
pragma solidity ^0.4.11; import 'dapple/test.sol'; import 'dapple/reporter.sol'; import "./Test.DummyOptionConverter.sol"; import "./Test.Types.sol"; contract EmpReentry is Reporter { address _t; function _target( address target ) { _t = target; } function() payable { // malicious function that will withdraw again if (msg.gas < 21000) return; // do not even try to proceed with low gas limit //@info gas `uint msg.gas` balance `uint this.balance` //@info _t `address _t` msg.sender `address msg.sender` if (this.balance < 3 ether) { bool rv = msg.sender.call(bytes4(keccak256("withdraw()"))); //@info rv `bool rv` } } function employeeExerciseOptions(bool agreeToAccelConditions) returns (uint8){ return uint8(ESOP(_t).employeeExerciseOptions(agreeToAccelConditions)); } function employeeSignsToESOP() returns (uint8){ return uint8(ESOP(_t).employeeSignsToESOP()); } function malicious_withdraw() returns (uint) { bool rv = _t.call(bytes4(keccak256("withdraw()"))); } } contract TestOptionConverters is Test, ESOPMaker, Reporter, ESOPTypes, Math { EmpTester emp1; ESOP esop; function setUp() { emp1 = new EmpTester(); //emp2 = new Tester(); esop = makeNFESOP(); emp1._target(esop); } function procERC20OptionsConverter(ERC20OptionsConverter converter, uint32 ct) returns (EmpTester, EmpTester, EmpTester) { esop.offerOptionsToEmployee(emp1, ct, ct + 2 weeks, 100, false); EmpTester emp2 = new EmpTester(); esop.offerOptionsToEmployee(emp2, ct, ct + 2 weeks, 400, false); EmpTester emp3 = new EmpTester(); esop.offerOptionsToEmployee(emp3, ct, ct + 2 weeks, 800, false); uint poolOptions = esop.totalPoolOptions() - esop.remainingPoolOptions(); uint extraOptions = esop.totalExtraOptions(); emp1._target(esop); emp2._target(esop); emp3._target(esop); uint rc = uint(emp1.employeeSignsToESOP()); assertEq(rc, 0, "emp signs"); emp2.employeeSignsToESOP(); emp3.employeeSignsToESOP(); // convert after 3 years to erc20 token (tokenization scenario) ct += 3 years; esop.mockTime(ct); rc = uint(esop.offerOptionsConversion(converter)); assertEq(rc, 0, "converter"); uint32 cdead = converter.getExercisePeriodDeadline(); //convert all users emp1.employeeExerciseOptions(true); emp2.employeeExerciseOptions(true); emp3.employeeExerciseOptions(true); // all options converted + exit bonus if (absDiff(converter.totalSupply() - extraOptions, poolOptions + divRound(poolOptions*esop.optionsCalculator().bonusOptionsPromille(), esop.optionsCalculator().FP_SCALE())) > 1) { assertEq(converter.totalSupply() - extraOptions, poolOptions + divRound(poolOptions*esop.optionsCalculator().bonusOptionsPromille(), esop.optionsCalculator().FP_SCALE())); } return (emp1, emp2, emp3); } function testERC20OptionsConverterTransferBlocked() { uint32 deadlineDelta = 3 years + 4 weeks; uint32 ct = esop.currentTime(); ERC20OptionsConverter converter = new ERC20OptionsConverter(esop, ct + deadlineDelta, ct + 2*deadlineDelta); var (emp1, emp2, emp3) = procERC20OptionsConverter(converter, ct); // transfer function should be blocked uint emp1b = converter.balanceOf(emp1); uint emp2b = converter.balanceOf(emp2); if (emp1b == 0 || emp2b == 0) fail(); emp1._target(converter); uint g = 0; assembly { g:=gas } //@info gas left `uint g` bool rv = emp1.forward(bytes4(keccak256("transfer(address,uint256)")), address(emp2), emp1b); assertEq(rv, false); // if failed, minimum gas is left assembly { g:=gas } //@info gas left `uint g` //@info throw rv `bool rv` } function testERC20OptionsConverter() { uint32 deadlineDelta = 3 years + 4 weeks; uint32 ct = esop.currentTime(); ERC20OptionsConverter converter = new ERC20OptionsConverter(esop, ct + deadlineDelta, ct + 2*deadlineDelta); var (emp1, emp2, emp3) = procERC20OptionsConverter(converter, ct); // transfer function should be blocked uint emp1b = converter.balanceOf(emp1); uint emp2b = converter.balanceOf(emp2); if (emp1b == 0 || emp2b == 0) fail(); emp1._target(converter); // move to a moment when options are released ct += 2*deadlineDelta; converter.mockTime(ct); ERC20OptionsConverter(emp1).transfer(emp2, emp1b); assertEq(converter.balanceOf(emp1), 0); assertEq(converter.balanceOf(emp2), emp1b + emp2b); } function testProceedsOptionsConverter() { uint32 deadlineDelta = 3 years + 4 weeks; uint32 ct = esop.currentTime(); ProceedsOptionsConverter converter = new ProceedsOptionsConverter(esop, ct + deadlineDelta, ct + 2*deadlineDelta); var (emp1, emp2, emp3) = procERC20OptionsConverter(converter, ct); ct += 2*deadlineDelta; converter.mockTime(ct); uint emp1b = converter.balanceOf(emp1); uint emp2b = converter.balanceOf(emp2); uint totsupp = converter.totalSupply(); //@info emp1b `uint emp1b` emp2b `uint emp2b` totsupp `uint totsupp` // 0 withdrawn before payout emp1._target(converter); uint cb = emp1.withdraw(); assertEq(cb, 0, "empty withdrawal"); // make few payouts converter.makePayout.value(2 ether)(); converter.makePayout.value(5 ether)(); cb = converter.balance; //@info balance `uint cb` assertEq(cb, 7 ether, "make payout"); // withdraw emp1 1 cb = emp1.withdraw(); //@info e1 payout `uint cb` assertEq(emp1.balance, cb, "e1 rv == balance"); uint expb = divRound(7 ether * emp1b, totsupp); if (absDiff(cb, expb) > 1) assertEq(cb, expb, "e1 withdraw amount"); converter.makePayout.value(1 ether)(); // emp2 should get share from 3 payouts emp2._target(converter); cb = emp2.withdraw(); expb = divRound(8 ether * emp2b, totsupp); if (absDiff(cb, expb) > 1) assertEq(cb, expb, "e2 withdraw amount"); // emp1 should get share from last payout cb = emp1.withdraw(); expb = divRound(1 ether * emp1b, totsupp); if (absDiff(cb, expb) > 1) assertEq(cb, expb, "e1 withdraw 3 payout"); // emp should get 0 cb = emp1.withdraw(); assertEq(cb, 0, "e1 withdraw 0"); cb = emp2.withdraw(); assertEq(cb, 0, "e2 withdraw 0"); // total ether invariant assertEq(8 ether, converter.balance + emp1.balance + emp2.balance, "total ether"); emp3._target(converter); cb = emp3.withdraw(); //@info emp3 payout `uint cb` assertEq(converter.balance, 0, "all paid out"); } function testThrowProceedsWithdrawnTransferFrom() { uint32 deadlineDelta = 3 years + 4 weeks; uint32 ct = esop.currentTime(); ProceedsOptionsConverter converter = new ProceedsOptionsConverter(esop, ct + deadlineDelta, ct + 2*deadlineDelta); var (emp1, emp2, emp3) = procERC20OptionsConverter(converter, ct); ct += deadlineDelta; converter.mockTime(ct); uint emp1b = converter.balanceOf(emp1); converter.makePayout.value(5 ether)(); emp1._target(converter); uint cb = emp1.withdraw(); // should throw ERC20OptionsConverter(emp1).transfer(emp2, emp1b); } function testThrowProceedsWithdrawnTransferTo() { uint32 deadlineDelta = 3 years + 4 weeks; uint32 ct = esop.currentTime(); ProceedsOptionsConverter converter = new ProceedsOptionsConverter(esop, ct + deadlineDelta, ct + 2*deadlineDelta); var (emp1, emp2, emp3) = procERC20OptionsConverter(converter, ct); ct += deadlineDelta; converter.mockTime(ct); uint emp1b = converter.balanceOf(emp1); uint emp2b = converter.balanceOf(emp2); converter.makePayout.value(5 ether)(); emp1._target(converter); emp2._target(converter); uint cb = emp1.withdraw(); // should throw ERC20OptionsConverter(emp2).transfer(emp1, emp2b); } function testProceedsWithdrawalReentry() { EmpReentry emp1 = new EmpReentry(); EmpTester emp0 = new EmpTester(); EmpTester empx = new EmpTester(); uint32 ct = esop.currentTime(); esop.offerOptionsToEmployee(emp0, ct, ct + 2 weeks, 100, false); esop.offerOptionsToEmployee(empx, ct, ct + 2 weeks, 400, false); esop.offerOptionsToEmployee(emp1, ct, ct + 2 weeks, 2876, false); emp1._target(esop); emp1.employeeSignsToESOP(); emp0._target(esop); empx._target(esop); emp0.employeeSignsToESOP(); empx.employeeSignsToESOP(); esop.mockTime(ct + 3 years); uint32 deadlineDelta = 3 years + 4 weeks; ProceedsOptionsConverter converter = new ProceedsOptionsConverter(esop, ct + deadlineDelta, ct + 2*deadlineDelta); uint rc = uint(esop.offerOptionsConversion(converter)); assertEq(rc, 0, "converter"); emp1.employeeExerciseOptions(true); emp0.employeeExerciseOptions(true); empx.employeeExerciseOptions(true); converter.mockTime(ct + 2*deadlineDelta); // now emp1 tries to withdraw multiple times uint emp1b = converter.balanceOf(emp1); converter.makePayout.value(5 ether)(); emp1._target(converter); emp1.malicious_withdraw(); //uint cb = emp1.withdraw(); uint expbalance = divRound((5 ether * emp1b), converter.totalSupply()); assertEq(emp1.balance, expbalance, "no re-entry"); uint stolen = emp1.balance - expbalance; //@warn `uint stolen` wei stolen //assertEq(cb, emp1.balance, "faithful rv"); } function testProceedsOptionsConverterOptionsDenied() { uint32 ct = esop.currentTime(); esop.offerOptionsToEmployee(emp1, ct, ct + 2 weeks, 1289, false); uint emp1issued = esop.totalPoolOptions() - esop.remainingPoolOptions(); emp1.employeeSignsToESOP(); uint32 vestp = uint32(esop.optionsCalculator().vestingPeriod()); esop.mockTime(ct + vestp / 2); uint32 deadlineDelta = vestp / 2 + 4 weeks; ProceedsOptionsConverter converter = new ProceedsOptionsConverter(esop, ct + deadlineDelta, ct + deadlineDelta + 1 weeks); // options offered in half of the vesting uint rc = uint(esop.offerOptionsConversion(converter)); assertEq(rc, 0, "converter"); // agrees to accel vesting rc = uint(emp1.employeeDenyExerciseOptions()); assertEq(rc, 0, "deny exercise"); // total supply should be 0 assertEq(converter.totalSupply(), 0); // burned to 0 address 0 options assertEq(converter.balanceOf(address(0)), 0); } }
do not even try to proceed with low gas limit
if (msg.gas < 21000) return;
13,121,200
[ 1, 2896, 486, 5456, 775, 358, 11247, 598, 4587, 16189, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 3576, 18, 31604, 411, 9035, 3784, 13, 327, 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 ]
// SPDX-License-Identifier: Unlicense pragma solidity ^0.7.0; contract killcord { string version; string publishedKey; string payloadEndpoint; uint lastCheckIn; address payable owner; address publisher; bool lockPublishedKey; bool lockPayloadEndpoint; // set the `owner` of the contract and log first `checkIn` constructor(address p) { owner = msg.sender; publisher = p; version = "0.0.1"; checkIn(); } // a function modifier used to restrict most write functions to only // the contract owner modifier onlyOwner { require(msg.sender == owner); _; } // a function modifier used to restrict publishing the key to only // the owner or publisher addresses modifier onlyOwnerOrPublisher { bool ok = false; if (msg.sender == publisher) { ok = true; } if (msg.sender == owner) { ok = true; } require(ok == true); _; } // This function is restricted to work with only the contract owner. // friends don't let friends deploy contracts that can't be killed function kill() public onlyOwner { selfdestruct(owner); } // This function is restricted to work with only the contract owner. // `block.timestamp` is known to tolerate datestamp drift of up to // 900 seconds at the time of this writing, consider then when // setting TTL thresholds for the publisher. function checkIn() public onlyOwner { lastCheckIn = block.timestamp; } // Outputs the `uint` for the last `block.timestamp` // that registered to this contract on the blockchain. function getLastCheckIn() public view returns (uint) { return lastCheckIn; } // Outputs the `string` for the last `block.timestamp` // that registered to this contract on the blockchain. function getPayloadEndpoint() public view returns (string memory) { return payloadEndpoint; } // This function is restricted to work with only the contract owner. // Sets the Payload Endpoint after checking max length of the string. // sets lockPayloadEndpoint to TRUE so that once set, this value can // not be changed. function setPayloadEndpoint(string memory s) public onlyOwner { uint max = 512; require(bytes(s).length <= max); require(lockPayloadEndpoint == false); payloadEndpoint = s; lockPayloadEndpoint = true; } // getKey() simply outputs the `publishedKey` saved to the blockChain function getKey() public view returns (string memory) { return publishedKey; } function getOwner() public view returns (address) { return owner; } function getPublisher() public view returns (address) { return publisher; } function getVersion() public view returns (string memory) { return version; } // This function is restricted to work with only the contract owner. function setKey(string memory k) public onlyOwnerOrPublisher { uint max = 128; require(bytes(k).length <= max); require(lockPublishedKey == false); publishedKey = k; lockPublishedKey = true; } }
This function is restricted to work with only the contract owner.
function setKey(string memory k) public onlyOwnerOrPublisher { uint max = 128; require(bytes(k).length <= max); require(lockPublishedKey == false); publishedKey = k; lockPublishedKey = true; }
12,534,958
[ 1, 2503, 445, 353, 15693, 358, 1440, 598, 1338, 326, 6835, 3410, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16696, 12, 1080, 3778, 417, 13, 1071, 1338, 5541, 1162, 15960, 288, 203, 565, 2254, 943, 273, 8038, 31, 203, 565, 2583, 12, 3890, 12, 79, 2934, 2469, 1648, 943, 1769, 203, 565, 2583, 12, 739, 16451, 653, 422, 629, 1769, 203, 565, 9487, 653, 273, 417, 31, 203, 565, 2176, 16451, 653, 273, 638, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xa735224e43Cb2549438275e985ef67FA9FCf3c8C/sources/LidTimeLock.sol
Refund eth in case final purchase needed to end sale without dust errors
function deposit(address payable referrer) public payable nonReentrant whenNotPaused { require(timer.isStarted(), "Presale not yet started."); require(now >= access.getAccessTime(msg.sender, timer.startTime()), "Time must be at least access time."); require(msg.sender != referrer, "Sender cannot be referrer."); require(address(this).balance.sub(msg.value) <= hardcap, "Cannot deposit more than hardcap."); require(!hasSentToUniswap, "Presale Ended, Uniswap has been called."); uint endTime = timer.endTime(); require(!(now > endTime && endTime != 0), "Presale Ended, time over limit."); require( redeemer.accountDeposits(msg.sender).add(msg.value) <= maxBuyPerAddress, "Deposit exceeds max buy per address." ); bool _isRefunding = timer.updateRefunding(); if(_isRefunding) { _startRefund(); return; } uint depositEther = msg.value; uint excess = 0; if (address(this).balance > hardcap) { excess = address(this).balance.sub(hardcap); depositEther = depositEther.sub(excess); } redeemer.setDeposit(msg.sender, depositEther); if (excess != 0) { msg.sender.transfer(excess); } }
2,816,059
[ 1, 21537, 13750, 316, 648, 727, 23701, 3577, 358, 679, 272, 5349, 2887, 302, 641, 1334, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 12, 2867, 8843, 429, 14502, 13, 1071, 8843, 429, 1661, 426, 8230, 970, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 12542, 18, 291, 9217, 9334, 315, 12236, 5349, 486, 4671, 5746, 1199, 1769, 203, 3639, 2583, 12, 3338, 1545, 2006, 18, 588, 1862, 950, 12, 3576, 18, 15330, 16, 5441, 18, 1937, 950, 1435, 3631, 315, 950, 1297, 506, 622, 4520, 2006, 813, 1199, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 14502, 16, 315, 12021, 2780, 506, 14502, 1199, 1769, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 18, 1717, 12, 3576, 18, 1132, 13, 1648, 7877, 5909, 16, 315, 4515, 443, 1724, 1898, 2353, 7877, 5909, 1199, 1769, 203, 3639, 2583, 12, 5, 5332, 7828, 774, 984, 291, 91, 438, 16, 315, 12236, 5349, 1374, 785, 16, 1351, 291, 91, 438, 711, 2118, 2566, 1199, 1769, 203, 3639, 2254, 13859, 273, 5441, 18, 409, 950, 5621, 203, 3639, 2583, 12, 5, 12, 3338, 405, 13859, 597, 13859, 480, 374, 3631, 315, 12236, 5349, 1374, 785, 16, 813, 1879, 1800, 1199, 1769, 203, 3639, 2583, 12, 203, 5411, 283, 24903, 264, 18, 4631, 758, 917, 1282, 12, 3576, 18, 15330, 2934, 1289, 12, 3576, 18, 1132, 13, 1648, 943, 38, 9835, 2173, 1887, 16, 203, 5411, 315, 758, 1724, 14399, 943, 30143, 1534, 1758, 1199, 203, 3639, 11272, 203, 3639, 1426, 389, 291, 1957, 14351, 273, 5441, 18, 2725, 1957, 14351, 5621, 203, 3639, 309, 24899, 291, 1957, 14351, 13, 288, 203, 5411, 389, 1937, 21537, 2 ]
./full_match/1/0x2a4A4f6330b30f257146bb0bc6e57019b8ddbE78/sources/contracts/OwnableUpgradeable.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); function __Ownable_init(address owner_) internal onlyInitializing { __Ownable_init_unchained(owner_); } function __Ownable_init_unchained(address owner_) internal onlyInitializing { _transferOwnership(owner_); } modifier onlyOwner() { _checkOwner(); _; } function owner() public view virtual returns (address) { return _owner; } function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; }
4,904,463
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 10784, 429, 353, 10188, 6934, 16, 1772, 10784, 429, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 203, 565, 445, 1001, 5460, 429, 67, 2738, 12, 2867, 3410, 67, 13, 2713, 1338, 29782, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 67, 4384, 8707, 12, 8443, 67, 1769, 203, 565, 289, 203, 203, 565, 445, 1001, 5460, 429, 67, 2738, 67, 4384, 8707, 12, 2867, 3410, 67, 13, 2713, 1338, 29782, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 8443, 67, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 389, 1893, 5541, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 389, 1893, 5541, 1435, 2713, 1476, 5024, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2867, 12, 20, 10019, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 2 ]
./partial_match/56/0xBcbe231dF846A7CAAbFe6492a629447a0d4c9c6d/sources/Lottery.sol
Withdraw without caring about rewards. EMERGENCY ONLY.
function adminWithdraw(uint256 _amount) public onlyAdmin { bdo.safeTransfer(address(msg.sender), _amount); emit DevWithdraw(msg.sender, _amount); }
11,068,185
[ 1, 1190, 9446, 2887, 5926, 310, 2973, 283, 6397, 18, 7141, 654, 16652, 16068, 20747, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3981, 1190, 9446, 12, 11890, 5034, 389, 8949, 13, 1071, 1338, 4446, 288, 203, 3639, 324, 2896, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 3626, 9562, 1190, 9446, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xD7E757Daf1ad562b01C35CC28B65876641CCAd39/sources/contracts/recipes/Deed.sol
* @dev See {IDeed-merge}./
function merge(uint256[] calldata tokenIds) external override nonReentrant { uint256 newToken = ++_currentTokenId; uint256 resourcesLength = _resources.length(); uint256 tokensLength = tokenIds.length; require( tokenIds.length > 1, "At least two tokens are required for merging" ); for (uint i = 0; i < tokensLength; ) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Nonexistent or duplicated token"); require(ownerOf(tokenId) == msg.sender, "Not owner"); for (uint j = 0; j < resourcesLength; ) { uint256 resourceId = _resources.at(j); uint256 contribution = _deedContributionCount[tokenId][ resourceId ]; if (contribution > 0) { delete _deedContributionCount[tokenId][resourceId]; } _deedContributionCount[newToken][resourceId] += contribution; unchecked { j++; } } _burn(tokenId); unchecked { i++; } } _mint(msg.sender, newToken); for (uint i = 0; i < tokensLength; ) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Nonexistent or duplicated token"); require(ownerOf(tokenId) == msg.sender, "Not owner"); for (uint j = 0; j < resourcesLength; ) { uint256 resourceId = _resources.at(j); uint256 contribution = _deedContributionCount[tokenId][ resourceId ]; if (contribution > 0) { delete _deedContributionCount[tokenId][resourceId]; } _deedContributionCount[newToken][resourceId] += contribution; unchecked { j++; } } _burn(tokenId); unchecked { i++; } } _mint(msg.sender, newToken); for (uint i = 0; i < tokensLength; ) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Nonexistent or duplicated token"); require(ownerOf(tokenId) == msg.sender, "Not owner"); for (uint j = 0; j < resourcesLength; ) { uint256 resourceId = _resources.at(j); uint256 contribution = _deedContributionCount[tokenId][ resourceId ]; if (contribution > 0) { delete _deedContributionCount[tokenId][resourceId]; } _deedContributionCount[newToken][resourceId] += contribution; unchecked { j++; } } _burn(tokenId); unchecked { i++; } } _mint(msg.sender, newToken); for (uint i = 0; i < tokensLength; ) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Nonexistent or duplicated token"); require(ownerOf(tokenId) == msg.sender, "Not owner"); for (uint j = 0; j < resourcesLength; ) { uint256 resourceId = _resources.at(j); uint256 contribution = _deedContributionCount[tokenId][ resourceId ]; if (contribution > 0) { delete _deedContributionCount[tokenId][resourceId]; } _deedContributionCount[newToken][resourceId] += contribution; unchecked { j++; } } _burn(tokenId); unchecked { i++; } } _mint(msg.sender, newToken); for (uint i = 0; i < tokensLength; ) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Nonexistent or duplicated token"); require(ownerOf(tokenId) == msg.sender, "Not owner"); for (uint j = 0; j < resourcesLength; ) { uint256 resourceId = _resources.at(j); uint256 contribution = _deedContributionCount[tokenId][ resourceId ]; if (contribution > 0) { delete _deedContributionCount[tokenId][resourceId]; } _deedContributionCount[newToken][resourceId] += contribution; unchecked { j++; } } _burn(tokenId); unchecked { i++; } } _mint(msg.sender, newToken); }
17,177,499
[ 1, 9704, 288, 734, 73, 329, 17, 2702, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2691, 12, 11890, 5034, 8526, 745, 892, 1147, 2673, 13, 3903, 3849, 1661, 426, 8230, 970, 288, 203, 3639, 2254, 5034, 394, 1345, 273, 965, 67, 2972, 1345, 548, 31, 203, 3639, 2254, 5034, 2703, 1782, 273, 389, 4683, 18, 2469, 5621, 203, 3639, 2254, 5034, 2430, 1782, 273, 1147, 2673, 18, 2469, 31, 203, 3639, 2583, 12, 203, 5411, 1147, 2673, 18, 2469, 405, 404, 16, 203, 5411, 315, 861, 4520, 2795, 2430, 854, 1931, 364, 17256, 6, 203, 3639, 11272, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2430, 1782, 31, 262, 288, 203, 5411, 2254, 5034, 1147, 548, 273, 1147, 2673, 63, 77, 15533, 203, 5411, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 3989, 19041, 578, 16975, 1147, 8863, 203, 5411, 2583, 12, 8443, 951, 12, 2316, 548, 13, 422, 1234, 18, 15330, 16, 315, 1248, 3410, 8863, 203, 203, 5411, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 2703, 1782, 31, 262, 288, 203, 7734, 2254, 5034, 15035, 273, 389, 4683, 18, 270, 12, 78, 1769, 203, 7734, 2254, 5034, 24880, 273, 389, 323, 329, 442, 4027, 1380, 63, 2316, 548, 6362, 203, 10792, 15035, 203, 7734, 308, 31, 203, 7734, 309, 261, 591, 4027, 405, 374, 13, 288, 203, 10792, 1430, 389, 323, 329, 442, 4027, 1380, 63, 2316, 548, 6362, 3146, 548, 15533, 203, 7734, 289, 203, 7734, 389, 323, 329, 442, 4027, 1380, 63, 2704, 1345, 6362, 3146, 548, 65, 1011, 24880, 31, 203, 7734, 22893, 288, 203, 10792, 525, 2 ]
./partial_match/5/0x537637a09bB98D73FeEd26E41D53e8223c1925c8/sources/contracts/CantoPals.sol
Only owner can execute these functions. */
function revealCollection() public onlyOwner { isRevealed = true; }
16,859,173
[ 1, 3386, 3410, 848, 1836, 4259, 4186, 18, 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, 565, 445, 283, 24293, 2532, 1435, 1071, 1338, 5541, 288, 203, 3639, 28627, 537, 18931, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x0449997C9ea22837d9BEB0998Fec835D5329BE2d/sources/contracts/mXENx/mXEN/XENCrypto.sol
* @dev calculates Withdrawal Penalty depending on lateness/ =MIN(2^(daysLate+3)/window-1,99)
function _penalty(uint256 secsLate) private pure returns (uint256) { uint256 daysLate = secsLate / SECONDS_IN_DAY; if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT; uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1; return Math.min(penalty, MAX_PENALTY_PCT); }
9,513,666
[ 1, 12780, 815, 3423, 9446, 287, 453, 275, 15006, 8353, 603, 2516, 15681, 19, 273, 6236, 12, 22, 29020, 9810, 48, 340, 15, 23, 13176, 5668, 17, 21, 16, 2733, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1907, 15006, 12, 11890, 5034, 18043, 48, 340, 13, 3238, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 4681, 48, 340, 273, 18043, 48, 340, 342, 17209, 67, 706, 67, 10339, 31, 203, 3639, 309, 261, 9810, 48, 340, 405, 13601, 40, 10821, 1013, 67, 23407, 67, 31551, 300, 404, 13, 327, 4552, 67, 52, 1157, 1013, 5538, 67, 52, 1268, 31, 203, 3639, 2254, 5034, 23862, 273, 261, 11890, 5034, 12, 21, 13, 2296, 261, 9810, 48, 340, 397, 890, 3719, 342, 203, 5411, 13601, 40, 10821, 1013, 67, 23407, 67, 31551, 300, 203, 5411, 404, 31, 203, 3639, 327, 2361, 18, 1154, 12, 1907, 15006, 16, 4552, 67, 52, 1157, 1013, 5538, 67, 52, 1268, 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 ]
//Address: 0xcdf89e7f44fcc837630fb4a10387ca81eba6932a //Contract name: MultiSigTokenWallet //Balance: 0 Ether //Verification Date: 8/27/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity 0.4.16; /// @title Multi signature token wallet - Allows multiple parties to approve tokens transfer /// @author popofe (Avalon Platform) - <[email protected]> contract MultiSigTokenWallet { /// @dev No fallback function to prevent ether deposit address constant public TOKEN = 0xeD247980396B10169BB1d36f6e278eD16700a60f; event Confirmation(address source, uint actionId); event Revocation(address source, uint actionId); event NewAction(uint actionId); event Execution(uint actionId); event ExecutionFailure(uint actionId); event OwnerAddition(address owner); event OwnerWithdraw(address owner); event QuorumChange(uint quorum); enum ActionChoices { AddOwner, ChangeQuorum, DeleteAction, TransferToken, WithdrawOwner} mapping (uint => Action) public actions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public quorum; uint public actionCount; struct Action { address addressField; uint value; ActionChoices actionType; bool executed; bool deleted; } modifier ownerDeclared(address owner) { require (isOwner[owner]); _; } modifier actionSubmitted(uint actionId) { require ( actions[actionId].addressField != 0 || actions[actionId].value != 0); _; } modifier confirmed(uint actionId, address owner) { require (confirmations[actionId][owner]); _; } modifier notConfirmed(uint actionId, address owner) { require (!confirmations[actionId][owner]); _; } modifier notExecuted(uint actionId) { require (!actions[actionId].executed); _; } modifier notDeleted(uint actionId) { require (!actions[actionId].deleted); _; } modifier validQuorum(uint ownerCount, uint _quorum) { require (_quorum <= ownerCount && _quorum > 0); _; } modifier validAction(address addressField, uint value, ActionChoices actionType) { require ((actionType == ActionChoices.AddOwner && addressField != 0 && value == 0) || (actionType == ActionChoices.ChangeQuorum && addressField == 0 && value > 0) || (actionType == ActionChoices.DeleteAction && addressField == 0 && value > 0) || (actionType == ActionChoices.TransferToken && addressField != 0 && value > 0) || (actionType == ActionChoices.WithdrawOwner && addressField != 0 && value == 0)); _; } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _quorum Number of required confirmations. function MultiSigTokenWallet(address[] _owners, uint _quorum) public validQuorum(_owners.length, _quorum) { for (uint i=0; i<_owners.length; i++) { require (!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; quorum = _quorum; } /// @dev Allows to add a new owner. /// @param owner Address of new owner. function addOwner(address owner) private { require(!isOwner[owner]); isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to withdraw an owner. /// @param owner Address of owner. function withdrawOwner(address owner) private { require (isOwner[owner]); require (owners.length - 1 >= quorum); isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; OwnerWithdraw(owner); } /// @dev Allows to change the number of required confirmations. /// @param _quorum Number of required confirmations. function changeQuorum(uint _quorum) private { require (_quorum > 0 && _quorum <= owners.length); quorum = _quorum; QuorumChange(_quorum); } /// @dev Allows to delete a previous action not executed /// @param _actionId Number of required confirmations. function deleteAction(uint _actionId) private notExecuted(_actionId) { actions[_actionId].deleted = true; } /// @dev Allows to delete a previous action not executed /// @param _destination address that receive tokens. /// @param _value Number of tokens. function transferToken(address _destination, uint _value) private returns (bool) { ERC20Basic ERC20Contract = ERC20Basic(TOKEN); return ERC20Contract.transfer(_destination, _value); } /// @dev Allows an owner to submit and confirm a transaction. /// @param addressField Action target address. /// @param value Number of token / new quorum to reach. /// @return Returns transaction ID. function submitAction(address addressField, uint value, ActionChoices actionType) public ownerDeclared(msg.sender) validAction(addressField, value, actionType) returns (uint actionId) { actionId = addAction(addressField, value, actionType); confirmAction(actionId); } /// @dev Allows an owner to confirm a transaction. /// @param actionId Action ID. function confirmAction(uint actionId) public ownerDeclared(msg.sender) actionSubmitted(actionId) notConfirmed(actionId, msg.sender) { confirmations[actionId][msg.sender] = true; Confirmation(msg.sender, actionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param actionId Action ID. function revokeConfirmation(uint actionId) public ownerDeclared(msg.sender) confirmed(actionId, msg.sender) notExecuted(actionId) { confirmations[actionId][msg.sender] = false; Revocation(msg.sender, actionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param actionId Action ID. function executeAction(uint actionId) public ownerDeclared(msg.sender) actionSubmitted(actionId) notExecuted(actionId) notDeleted(actionId) { if (isConfirmed(actionId)) { Action memory action = actions[actionId]; action.executed = true; if (action.actionType == ActionChoices.AddOwner) addOwner(action.addressField); else if (action.actionType == ActionChoices.ChangeQuorum) changeQuorum(action.value); else if (action.actionType == ActionChoices.DeleteAction) deleteAction(action.value); else if (action.actionType == ActionChoices.TransferToken) if (transferToken(action.addressField, action.value)) Execution(actionId); else { ExecutionFailure(actionId); action.executed = false; } else if (action.actionType == ActionChoices.WithdrawOwner) withdrawOwner(action.addressField); else revert(); } } /// @dev Returns the confirmation status of a transaction. /// @param actionId Action ID. /// @return Confirmation status. function isConfirmed(uint actionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[actionId][owners[i]]) count += 1; if (count == quorum) return true; } return false; } /// @dev Adds a new action to the transaction list, if action does not exist yet. /// @param addressField address to send token or too add or withadraw as owner. /// @param value number of tokens (useful only for token transfer). /// @return Returns transaction ID. function addAction(address addressField, uint value, ActionChoices actionType) private returns (uint) { actionCount += 1; uint actionId = actionCount; actions[actionId] = Action({ addressField: addressField, value: value, actionType: actionType, executed: false, deleted: false }); NewAction(actionId); return actionId; } /// @dev Returns number of confirmations of an action. /// @param actionId Action ID. /// @return Number of confirmations. function getConfirmationCount(uint actionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[actionId][owners[i]]) count += 1; } /// @dev Returns total number of actions after filers are applied. /// @param pending Include pending actions. /// @param executed Include executed actions. /// @return Total number of actions after filters are applied. function getActionCount(bool pending, bool executed, bool exceptDeleted) public constant returns (uint count) { for (uint i=0; i<actionCount; i++) if ( ((pending && !actions[i].executed) || (executed && actions[i].executed)) && (!exceptDeleted || !actions[i].deleted)) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param actionId Action ID. /// @return Returns array of owner addresses. function getConfirmations(uint actionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[actionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of action IDs in defined range. /// @param pending Include pending actions. /// @param executed Include executed actions. /// @param exceptDeleted Exclude deleted actions. /// @return Returns array of transaction IDs. function getActionIds(bool pending, bool executed, bool exceptDeleted) public constant returns (uint[] memory) { uint[] memory actionIds; uint count = 0; uint i; for (i=0; i<actionCount; i++) if (((pending && !actions[i].executed) || (executed && actions[i].executed)) && (!exceptDeleted || !actions[i].deleted)) { actionIds[count] = i; count += 1; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); }
@dev Allows to add a new owner. @param owner Address of new owner.
function addOwner(address owner) private { require(!isOwner[owner]); isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); }
1,831,514
[ 1, 19132, 358, 527, 279, 394, 3410, 18, 225, 3410, 5267, 434, 394, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 5541, 12, 2867, 3410, 13, 203, 3639, 3238, 203, 565, 288, 203, 3639, 2583, 12, 5, 291, 5541, 63, 8443, 19226, 203, 3639, 353, 5541, 63, 8443, 65, 273, 638, 31, 203, 3639, 25937, 18, 6206, 12, 8443, 1769, 203, 3639, 16837, 30296, 12, 8443, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-27 */ /** *Submitted for verification at Etherscan.io on 2021-04-13 */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT 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; } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @dev 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); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } /** * @notice Access Controls contract for the Digitalax Platform * @author BlockRocket.tech */ contract DigitalaxAccessControls is AccessControl { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant VERIFIED_MINTER_ROLE = keccak256("VERIFIED_MINTER_ROLE"); /// @notice Events for adding and removing various roles event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); event VerifiedMinterRoleGranted( address indexed beneficiary, address indexed caller ); event VerifiedMinterRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the verified minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasVerifiedMinterRole(address _address) external view returns (bool) { return hasRole(VERIFIED_MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the verified minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addVerifiedMinterRole(address _address) external { grantRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the verified minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeVerifiedMinterRole(address _address) external { revokeRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } } interface IStateSender { function syncState(address receiver, bytes calldata data) external; } library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } } contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2 ** proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } index = index / 2; } return computedHash == rootHash; } } abstract contract BaseRootTunnel { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using SafeMath for uint256; DigitalaxAccessControls public accessControls; // keccak256(MessageSent(bytes)) bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; // state sender contract IStateSender public stateSender; // root chain manager ICheckpointManager public checkpointManager; // child tunnel contract which receives and sends messages address public childTunnel; // storage to avoid duplicate exits mapping(bytes32 => bool) public processedExits; constructor(DigitalaxAccessControls _accessControls, address _stateSender) public { // _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // _setupContractId("RootTunnel"); accessControls = _accessControls; stateSender = IStateSender(_stateSender); } /** * @notice Set the state sender, callable only by admins * @dev This should be the state sender from plasma contracts * It is used to send bytes from root to child chain * @param newStateSender address of state sender contract */ function setStateSender(address newStateSender) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setStateSender: Sender must have the admin role" ); stateSender = IStateSender(newStateSender); } /** * @notice Set the checkpoint manager, callable only by admins * @dev This should be the plasma contract responsible for keeping track of checkpoints * @param newCheckpointManager address of checkpoint manager contract */ function setCheckpointManager(address newCheckpointManager) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setCheckpointManager: Sender must have the admin role" ); checkpointManager = ICheckpointManager(newCheckpointManager); } /** * @notice Set the child chain tunnel, callable only by admins * @dev This should be the contract responsible to receive data bytes on child chain * @param newChildTunnel address of child tunnel contract */ function setChildTunnel(address newChildTunnel) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setChildTunnel: Sender must have the admin role" ); require(newChildTunnel != address(0x0), "RootTunnel: INVALID_CHILD_TUNNEL_ADDRESS"); childTunnel = newChildTunnel; } /** * @notice Send bytes message to Child Tunnel * @param message bytes message that will be sent to Child Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToChild(bytes memory message) internal { stateSender.syncState(childTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( inputDataRLPList[2].toUint(), // blockNumber // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask inputDataRLPList[9].toUint() // receiptLogIndex ) ); require( processedExits[exitHash] == false, "RootTunnel: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3] .toList()[ inputDataRLPList[9].toUint() // receiptLogIndex ]; RLPReader.RLPItem[] memory logRLPList = logRLP.toList(); // check child tunnel require(childTunnel == RLPReader.toAddress(logRLPList[0]), "RootTunnel: INVALID_CHILD_TUNNEL"); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "RootTunnel: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics require( bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "RootTunnel: INVALID_SIGNATURE" ); // received message data bytes memory receivedData = logRLPList[2].toBytes(); (bytes memory message) = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootTunnel: INVALID_HEADER" ); return createdAt; } /** * @notice receive message from L2 to L1, validated by proof * @dev This function verifies if the transaction actually happened on child chain * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } /** * @notice Process message received from Child Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Child Tunnel */ function _processMessageFromChild(bytes memory message) virtual internal; } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @dev 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. */ /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // Contract based from the following: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155.sol /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ * * @notice Modifications to uri logic made by BlockRocket.tech */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Token ID to its URI mapping (uint256 => string) internal tokenUris; // Token ID to its total supply mapping(uint256 => uint256) public tokenTotalSupply; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; constructor () public { // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. */ function uri(uint256 tokenId) external view override returns (string memory) { return tokenUris[tokenId]; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view 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 See {IERC1155-setApprovalForAll}. */ 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); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external 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" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external virtual override { require(ids.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, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for a given token ID */ function _setURI(uint256 tokenId, string memory newuri) internal virtual { tokenUris[tokenId] = newuri; emit URI(newuri, tokenId); } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); tokenTotalSupply[id] = tokenTotalSupply[id].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][to] = amount.add(_balances[id][to]); tokenTotalSupply[id] = tokenTotalSupply[id].add(amount); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); tokenTotalSupply[id] = tokenTotalSupply[id].sub(amount); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); tokenTotalSupply[id] = tokenTotalSupply[id].sub(amount); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(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 ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(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; } } // Based on: https://github.com/rocksideio/ERC998-ERC1155-TopDown/blob/695963195606304374015c49d166ab2fbeb42ea9/contracts/IERC998ERC1155TopDown.sol interface IERC998ERC1155TopDown is IERC1155Receiver { event ReceivedChild(address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId, uint256 amount); event TransferBatchChild(uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256[] childTokenIds, uint256[] amounts); function childContractsFor(uint256 tokenId) external view returns (address[] memory childContracts); function childIdsForOn(uint256 tokenId, address childContract) external view returns (uint256[] memory childIds); function childBalance(uint256 tokenId, address childContract, uint256 childTokenId) external view returns (uint256); } /** * @notice Mock child tunnel contract to receive and send message from L2 */ abstract contract BaseChildTunnel { modifier onlyStateSyncer() { require( msg.sender == 0x0000000000000000000000000000000000001001, "Child tunnel: caller is not the state syncer" ); _; } // MessageTunnel on L1 will get data from this event event MessageSent(bytes message); /** * @notice Receive state sync from matic contracts * @dev This method will be called by Matic chain internally. * This is executed without transaction using a system call. */ function onStateReceive(uint256, bytes memory message) public onlyStateSyncer{ _processMessageFromRoot(message); } /** * @notice Emit message that can be received on Root Tunnel * @dev Call the internal function when need to emit message * @param message bytes message that will be sent to Root Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToRoot(bytes memory message) internal { emit MessageSent(message); } /** * @notice Process message received from Root Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Root Tunnel */ function _processMessageFromRoot(bytes memory message) virtual internal; } /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function msgSender() internal virtual view returns (address payable); function versionRecipient() external virtual view returns (string memory); } /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; /* * require a function to be called through GSN only */ modifier trustedForwarderOnly() { require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder"); _; } function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function msgSender() internal override view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } } /** * @title Digitalax Garment NFT a.k.a. parent NFTs * @dev Issues ERC-721 tokens as well as being able to hold child 1155 tokens */ contract DigitalaxGarmentNFT is ERC721("DigitalaxNFT", "DTX"), ERC1155Receiver, IERC998ERC1155TopDown, BaseChildTunnel, BaseRelayRecipient { // @notice event emitted upon construction of this contract, used to bootstrap external indexers event DigitalaxGarmentNFTContractDeployed(); // @notice event emitted when token URI is updated event DigitalaxGarmentTokenUriUpdate( uint256 indexed _tokenId, string _tokenUri ); // @notice event emitted when a tokens primary sale occurs event TokenPrimarySalePriceSet( uint256 indexed _tokenId, uint256 _salePrice ); event WithdrawnBatch( address indexed user, uint256[] tokenIds ); /// @dev Child ERC1155 contract address ERC1155 public childContract; /// @dev current max tokenId uint256 public tokenIdPointer; /// @dev TokenID -> Designer address mapping(uint256 => address) public garmentDesigners; /// @dev TokenID -> Primary Ether Sale Price in Wei mapping(uint256 => uint256) public primarySalePrice; /// @dev ERC721 Token ID -> ERC1155 ID -> Balance mapping(uint256 => mapping(uint256 => uint256)) private balances; /// @dev ERC1155 ID -> ERC721 Token IDs that have a balance mapping(uint256 => EnumerableSet.UintSet) private childToParentMapping; /// @dev ERC721 Token ID -> ERC1155 child IDs owned by the token ID mapping(uint256 => EnumerableSet.UintSet) private parentToChildMapping; /// @dev max children NFTs a single 721 can hold uint256 public maxChildrenPerToken = 10; /// @dev limit batching of tokens due to gas limit restrictions uint256 public constant BATCH_LIMIT = 20; mapping (uint256 => bool) public withdrawnTokens; address public childChain; modifier onlyChildChain() { require( _msgSender() == childChain, "Child token: caller is not the child chain contract" ); _; } /// Required to govern who can call certain functions DigitalaxAccessControls public accessControls; /** @param _accessControls Address of the Digitalax access control contract @param _childContract ERC1155 the Digitalax child NFT contract 0xb5505a6d998549090530911180f38aC5130101c6 */ constructor(DigitalaxAccessControls _accessControls, ERC1155 _childContract, address _childChain, address _trustedForwarder) public { accessControls = _accessControls; childContract = _childContract; childChain = _childChain; trustedForwarder = _trustedForwarder; emit DigitalaxGarmentNFTContractDeployed(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /** @notice Mints a DigitalaxGarmentNFT AND when minting to a contract checks if the beneficiary is a 721 compatible @dev Only senders with either the minter or smart contract role can invoke this method @param _beneficiary Recipient of the NFT @param _tokenUri URI for the token being minted @param _designer Garment designer - will be required for issuing royalties from secondary sales @return uint256 The token ID of the token that was minted */ function mint(address _beneficiary, string calldata _tokenUri, address _designer) external returns (uint256) { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasMinterRole(_msgSender()), "DigitalaxGarmentNFT.mint: Sender must have the minter or contract role" ); // Valid args _assertMintingParamsValid(_tokenUri, _designer); tokenIdPointer = tokenIdPointer.add(1); uint256 tokenId = tokenIdPointer; // MATIC guard, to catch tokens minted on chain require(!withdrawnTokens[tokenId], "ChildMintableERC721: TOKEN_EXISTS_ON_ROOT_CHAIN"); // Mint token and set token URI _safeMint(_beneficiary, tokenId); _setTokenURI(tokenId, _tokenUri); // Associate garment designer garmentDesigners[tokenId] = _designer; return tokenId; } /** @notice Burns a DigitalaxGarmentNFT, releasing any composed 1155 tokens held by the token itself @dev Only the owner or an approved sender can call this method @param _tokenId the token ID to burn */ function burn(uint256 _tokenId) public { address operator = _msgSender(); require( ownerOf(_tokenId) == operator || isApproved(_tokenId, operator), "DigitalaxGarmentNFT.burn: Only garment owner or approved" ); // If there are any children tokens then send them as part of the burn if (parentToChildMapping[_tokenId].length() > 0) { // Transfer children to the burner _extractAndTransferChildrenFromParent(_tokenId, _msgSender()); } // Destroy token mappings _burn(_tokenId); // Clean up designer mapping delete garmentDesigners[_tokenId]; delete primarySalePrice[_tokenId]; } /** @notice Single ERC1155 receiver callback hook, used to enforce children token binding to a given parent token */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) virtual external override returns (bytes4) { require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId = _extractIncomingTokenId(); _validateReceiverParams(_receiverTokenId, _operator, _from); _receiveChild(_receiverTokenId, _msgSender(), _id, _amount); emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _id, _amount); // Check total tokens do not exceed maximum require( parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken, "Cannot exceed max child token allocation" ); return this.onERC1155Received.selector; } /** @notice Batch ERC1155 receiver callback hook, used to enforce child token bindings to a given parent token ID */ function onERC1155BatchReceived(address _operator, address _from, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) virtual external override returns (bytes4) { require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId = _extractIncomingTokenId(); _validateReceiverParams(_receiverTokenId, _operator, _from); // Note: be mindful of GAS limits for (uint256 i = 0; i < _ids.length; i++) { _receiveChild(_receiverTokenId, _msgSender(), _ids[i], _values[i]); emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _ids[i], _values[i]); } // Check total tokens do not exceed maximum require( parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken, "Cannot exceed max child token allocation" ); return this.onERC1155BatchReceived.selector; } function _extractIncomingTokenId() internal pure returns (uint256) { // Extract out the embedded token ID from the sender uint256 _receiverTokenId; uint256 _index = msg.data.length - 32; assembly {_receiverTokenId := calldataload(_index)} return _receiverTokenId; } function _validateReceiverParams(uint256 _receiverTokenId, address _operator, address _from) internal view { require(_exists(_receiverTokenId), "Token does not exist"); // We only accept children from the Digitalax child contract require(_msgSender() == address(childContract), "Invalid child token contract"); // check the sender is the owner of the token or its just been birthed to this token if (_from != address(0)) { require( ownerOf(_receiverTokenId) == _from, "Cannot add children to tokens you dont own" ); // Check the operator is also the owner, preventing an approved address adding tokens on the holders behalf require(_operator == _from, "Operator is not owner"); } } ////////// // Admin / ////////// /** @notice Updates the token URI of a given token @dev Only admin or smart contract @param _tokenId The ID of the token being updated @param _tokenUri The new URI */ function setTokenURI(uint256 _tokenId, string calldata _tokenUri) external { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setTokenURI: Sender must be an authorised contract or admin" ); _setTokenURI(_tokenId, _tokenUri); emit DigitalaxGarmentTokenUriUpdate(_tokenId, _tokenUri); } /** @notice Records the Ether price that a given token was sold for (in WEI) @dev Only admin or a smart contract can call this method @param _tokenId The ID of the token being updated @param _salePrice The primary Ether sale price in WEI */ function setPrimarySalePrice(uint256 _tokenId, uint256 _salePrice) external { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setPrimarySalePrice: Sender must be an authorised contract or admin" ); require(_exists(_tokenId), "DigitalaxGarmentNFT.setPrimarySalePrice: Token does not exist"); require(_salePrice > 0, "DigitalaxGarmentNFT.setPrimarySalePrice: Invalid sale price"); // Only set it once if (primarySalePrice[_tokenId] == 0) { primarySalePrice[_tokenId] = _salePrice; emit TokenPrimarySalePriceSet(_tokenId, _salePrice); } } /** @notice Method for updating the access controls contract used by the NFT @dev Only admin @param _accessControls Address of the new access controls contract */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateAccessControls: Sender must be admin"); accessControls = _accessControls; } /** @notice Method for updating max children a token can hold @dev Only admin @param _maxChildrenPerToken uint256 the max children a token can hold */ function updateMaxChildrenPerToken(uint256 _maxChildrenPerToken) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateMaxChildrenPerToken: Sender must be admin"); maxChildrenPerToken = _maxChildrenPerToken; } ///////////////// // View Methods / ///////////////// /** @notice View method for checking whether a token has been minted @param _tokenId ID of the token being checked */ function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /** @dev Get the child token balances held by the contract, assumes caller knows the correct child contract */ function childBalance(uint256 _tokenId, address _childContract, uint256 _childTokenId) public view override returns (uint256) { return _childContract == address(childContract) ? balances[_tokenId][_childTokenId] : 0; } /** @dev Get list of supported child contracts, always a list of 0 or 1 in our case */ function childContractsFor(uint256 _tokenId) override external view returns (address[] memory) { if (!_exists(_tokenId)) { return new address[](0); } address[] memory childContracts = new address[](1); childContracts[0] = address(childContract); return childContracts; } /** @dev Gets mapped IDs for child tokens */ function childIdsForOn(uint256 _tokenId, address _childContract) override public view returns (uint256[] memory) { if (!_exists(_tokenId) || _childContract != address(childContract)) { return new uint256[](0); } uint256[] memory childTokenIds = new uint256[](parentToChildMapping[_tokenId].length()); for (uint256 i = 0; i < parentToChildMapping[_tokenId].length(); i++) { childTokenIds[i] = parentToChildMapping[_tokenId].at(i); } return childTokenIds; } /** @dev Get total number of children mapped to the token */ function totalChildrenMapped(uint256 _tokenId) external view returns (uint256) { return parentToChildMapping[_tokenId].length(); } /** * @dev checks the given token ID is approved either for all or the single token ID */ function isApproved(uint256 _tokenId, address _operator) public view returns (bool) { return isApprovedForAll(ownerOf(_tokenId), _operator) || getApproved(_tokenId) == _operator; } ///////////////////////// // Internal and Private / ///////////////////////// function _extractAndTransferChildrenFromParent(uint256 _fromTokenId, address _to) internal { uint256[] memory _childTokenIds = childIdsForOn(_fromTokenId, address(childContract)); uint256[] memory _amounts = new uint256[](_childTokenIds.length); for (uint256 i = 0; i < _childTokenIds.length; ++i) { uint256 _childTokenId = _childTokenIds[i]; uint256 amount = childBalance(_fromTokenId, address(childContract), _childTokenId); _amounts[i] = amount; _removeChild(_fromTokenId, address(childContract), _childTokenId, amount); } childContract.safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, abi.encodePacked("")); emit TransferBatchChild(_fromTokenId, _to, address(childContract), _childTokenIds, _amounts); } function _receiveChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private { if (balances[_tokenId][_childTokenId] == 0) { parentToChildMapping[_tokenId].add(_childTokenId); } balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].add(_amount); } function _removeChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private { require(_amount != 0 || balances[_tokenId][_childTokenId] >= _amount, "ERC998: insufficient child balance for transfer"); balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].sub(_amount); if (balances[_tokenId][_childTokenId] == 0) { childToParentMapping[_childTokenId].remove(_tokenId); parentToChildMapping[_tokenId].remove(_childTokenId); } } /** @notice Checks that the URI is not empty and the designer is a real address @param _tokenUri URI supplied on minting @param _designer Address supplied on minting */ function _assertMintingParamsValid(string calldata _tokenUri, address _designer) pure internal { require(bytes(_tokenUri).length > 0, "DigitalaxGarmentNFT._assertMintingParamsValid: Token URI is empty"); require(_designer != address(0), "DigitalaxGarmentNFT._assertMintingParamsValid: Designer is zero address"); } /** * @notice called when token is deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokenId for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded tokenId */ function deposit(address user, bytes calldata depositData) external onlyChildChain { // deposit single if (depositData.length == 32) { uint256 tokenId = abi.decode(depositData, (uint256)); withdrawnTokens[tokenId] = false; _safeMint(user, tokenId); // deposit batch } else { uint256[] memory tokenIds = abi.decode(depositData, (uint256[])); uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { withdrawnTokens[tokenIds[i]] = false; _safeMint(user, tokenIds[i]); } } } /** * @notice called when user wants to withdraw token back to root chain * @dev Should burn user's token. This transaction will be verified when exiting on root chain * @param tokenId tokenId to withdraw */ function withdraw(uint256 tokenId) external { withdrawnTokens[tokenId] = true; burn(tokenId); } /** * @notice called when user wants to withdraw multiple tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param tokenIds tokenId list to withdraw */ function withdrawBatch(uint256[] calldata tokenIds) external { uint256 length = tokenIds.length; require(length <= BATCH_LIMIT, "ChildERC721: EXCEEDS_BATCH_LIMIT"); for (uint256 i; i < length; i++) { uint256 tokenId = tokenIds[i]; withdrawnTokens[tokenIds[i]] = true; burn(tokenId); } emit WithdrawnBatch(_msgSender(), tokenIds); } function _processMessageFromRoot(bytes memory message) internal override { uint256 _tokenId; uint256 _primarySalePrice; address _garmentDesigner; string memory _tokenUri; uint256[] memory _children; uint256[] memory _childrenBalances; (_tokenId, _primarySalePrice, _garmentDesigner, _tokenUri, _children, _childrenBalances) = abi.decode(message, (uint256, uint256, address, string, uint256[], uint256[])); // With the information above, rebuild the 721 token in matic! primarySalePrice[_tokenId] = _primarySalePrice; garmentDesigners[_tokenId] = _garmentDesigner; _setTokenURI(_tokenId, _tokenUri); for (uint256 i = 0; i< _children.length; i++) { _receiveChild(_tokenId, _msgSender(), _children[i], _childrenBalances[i]); } } // Send the nft to root - if it does not exist then we can handle it on that side function sendNFTToRoot(uint256 tokenId) external { uint256 _primarySalePrice = primarySalePrice[tokenId]; address _garmentDesigner= garmentDesigners[tokenId]; string memory _tokenUri = tokenURI(tokenId); uint256[] memory _children = childIdsForOn(tokenId, address(childContract)); uint256 len = _children.length; uint256[] memory childBalances = new uint256[](len); for( uint256 i; i< _children.length; i++){ childBalances[i] = childBalance(tokenId, address(childContract), _children[i]); } _sendMessageToRoot(abi.encode(tokenId, ownerOf(tokenId), _primarySalePrice, _garmentDesigner, _tokenUri, _children, childBalances)); } } //imported from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155Burnable.sol /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn(address account, uint256 id, uint256 amount) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, amount); } function burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, amounts); } } /** * @title Digitalax Materials NFT a.k.a. child NFTs * @dev Issues ERC-1155 tokens which can be held by the parent ERC-721 contract */ contract DigitalaxMaterials is ERC1155Burnable, BaseRelayRecipient { // @notice event emitted on contract creation event DigitalaxMaterialsDeployed(); // @notice a single child has been created event ChildCreated( uint256 indexed childId ); // @notice a batch of children have been created event ChildrenCreated( uint256[] childIds ); string public name; string public symbol; // @notice current token ID pointer uint256 public tokenIdPointer; // @notice enforcing access controls DigitalaxAccessControls public accessControls; address public childChain; modifier onlyChildChain() { require( _msgSender() == childChain, "Child token: caller is not the child chain contract" ); _; } constructor( string memory _name, string memory _symbol, DigitalaxAccessControls _accessControls, address _childChain, address _trustedForwarder ) public { name = _name; symbol = _symbol; accessControls = _accessControls; trustedForwarder = _trustedForwarder; childChain = _childChain; emit DigitalaxMaterialsDeployed(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMaterials.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /////////////////////////// // Creating new children // /////////////////////////// /** @notice Creates a single child ERC1155 token @dev Only callable with smart contact role @return id the generated child Token ID */ function createChild(string calldata _uri) external returns (uint256 id) { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.createChild: Sender must be smart contract" ); require(bytes(_uri).length > 0, "DigitalaxMaterials.createChild: URI is a blank string"); tokenIdPointer = tokenIdPointer.add(1); id = tokenIdPointer; _setURI(id, _uri); emit ChildCreated(id); } /** @notice Creates a batch of child ERC1155 tokens @dev Only callable with smart contact role @return tokenIds the generated child Token IDs */ function batchCreateChildren(string[] calldata _uris) external returns (uint256[] memory tokenIds) { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.batchCreateChildren: Sender must be smart contract" ); require(_uris.length > 0, "DigitalaxMaterials.batchCreateChildren: No data supplied in array"); uint256 urisLength = _uris.length; tokenIds = new uint256[](urisLength); for (uint256 i = 0; i < urisLength; i++) { string memory uri = _uris[i]; require(bytes(uri).length > 0, "DigitalaxMaterials.batchCreateChildren: URI is a blank string"); tokenIdPointer = tokenIdPointer.add(1); _setURI(tokenIdPointer, uri); tokenIds[i] = tokenIdPointer; } // Batched event for GAS savings emit ChildrenCreated(tokenIds); } ////////////////////////////////// // Minting of existing children // ////////////////////////////////// /** @notice Mints a single child ERC1155 tokens, increasing its supply by the _amount specified. msg.data along with the parent contract as the recipient can be used to map the created children to a given parent token @dev Only callable with smart contact role */ function mintChild(uint256 _childTokenId, uint256 _amount, address _beneficiary, bytes calldata _data) external { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.mintChild: Sender must be smart contract" ); require(bytes(tokenUris[_childTokenId]).length > 0, "DigitalaxMaterials.mintChild: Strand does not exist"); require(_amount > 0, "DigitalaxMaterials.mintChild: No amount specified"); _mint(_beneficiary, _childTokenId, _amount, _data); } /** @notice Mints a batch of child ERC1155 tokens, increasing its supply by the _amounts specified. msg.data along with the parent contract as the recipient can be used to map the created children to a given parent token @dev Only callable with smart contact role */ function batchMintChildren( uint256[] calldata _childTokenIds, uint256[] calldata _amounts, address _beneficiary, bytes calldata _data ) external { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.batchMintChildren: Sender must be smart contract" ); require(_childTokenIds.length == _amounts.length, "DigitalaxMaterials.batchMintChildren: Array lengths are invalid"); require(_childTokenIds.length > 0, "DigitalaxMaterials.batchMintChildren: No data supplied in arrays"); // Check the strands exist and no zero amounts for (uint256 i = 0; i < _childTokenIds.length; i++) { uint256 strandId = _childTokenIds[i]; require(bytes(tokenUris[strandId]).length > 0, "DigitalaxMaterials.batchMintChildren: Strand does not exist"); uint256 amount = _amounts[i]; require(amount > 0, "DigitalaxMaterials.batchMintChildren: Invalid amount"); } _mintBatch(_beneficiary, _childTokenIds, _amounts, _data); } function updateAccessControls(DigitalaxAccessControls _accessControls) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMaterials.updateAccessControls: Sender must be admin" ); require( address(_accessControls) != address(0), "DigitalaxMaterials.updateAccessControls: New access controls cannot be ZERO address" ); accessControls = _accessControls; } /** * @notice called when tokens are deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokens for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded ids array and amounts array */ function deposit(address user, bytes calldata depositData) external onlyChildChain { ( uint256[] memory ids, uint256[] memory amounts, bytes memory data ) = abi.decode(depositData, (uint256[], uint256[], bytes)); require(user != address(0x0), "DigitalaxMaterials: INVALID_DEPOSIT_USER"); _mintBatch(user, ids, amounts, data); } /** * @notice called when user wants to withdraw single token back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param id id to withdraw * @param amount amount to withdraw */ function withdrawSingle(uint256 id, uint256 amount) external { _burn(_msgSender(), id, amount); } /** * @notice called when user wants to batch withdraw tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param ids ids to withdraw * @param amounts amounts to withdraw */ function withdrawBatch(uint256[] calldata ids, uint256[] calldata amounts) external { _burnBatch(_msgSender(), ids, amounts); } } contract DigitalaxRootTunnel is BaseRootTunnel { DigitalaxGarmentNFT public nft; DigitalaxMaterials public materials; /** @param _accessControls Address of the Digitalax access control contract */ constructor(DigitalaxAccessControls _accessControls, DigitalaxGarmentNFT _nft, DigitalaxMaterials _materials, address _stateSender) BaseRootTunnel(_accessControls, _stateSender) public { nft = _nft; materials = _materials; } function _processMessageFromChild(bytes memory message) internal override { address[] memory _owners; uint256[] memory _tokenIds; uint256[] memory _primarySalePrices; address[] memory _garmentDesigners; string[] memory _tokenUris; uint256[][] memory _children; string[][] memory _childrenURIs; uint256[][] memory _childrenBalances; ( _tokenIds, _owners, _primarySalePrices, _garmentDesigners, _tokenUris, _children, _childrenURIs, _childrenBalances) = abi.decode(message, (uint256[], address[], uint256[], address[], string[], uint256[][], string[][], uint256[][])); for( uint256 i; i< _tokenIds.length; i++){ // With the information above, rebuild the 721 token on mainnet if(!nft.exists(_tokenIds[i])){ uint256 newTokenId = nft.mint(_owners[i], _tokenUris[i], _garmentDesigners[i]); if(_primarySalePrices[i] > 0) { nft.setPrimarySalePrice(newTokenId, _primarySalePrices[i]); } if(_children[i].length > 0){ for( uint256 j; j< _children[i].length; j++){ uint256 newChildId = materials.createChild(_childrenURIs[i][j]); materials.mintChild(newChildId, _childrenBalances[i][j], address(nft), abi.encodePacked(newTokenId)); } } } } } // Send the nft to matic uint256[][] childNftIdArray; string[][] childNftURIArray; uint256[][] childNftBalanceArray; // For children nfts, these should be setup on the matic network before the 721 if there are any // This should be done before doing a classic matic deposit, that is why anyone can call it for now function transferNFTsDataToMatic(uint256[] memory _tokenIds) external { uint256 length = _tokenIds.length; uint256[] memory _salePrices = new uint256[](length); address[] memory _designers = new address[](length); string[] memory _tokenUris = new string[](length); for( uint256 i; i< _tokenIds.length; i++){ _salePrices[i] = nft.primarySalePrice(_tokenIds[i]); _designers[i] = nft.garmentDesigners(_tokenIds[i]); _tokenUris[i] = nft.tokenURI(_tokenIds[i]); } _sendMessageToChild(abi.encode(_tokenIds, _salePrices, _designers, _tokenUris)); } }
keccak256(MessageSent(bytes)) state sender contract root chain manager child tunnel contract which receives and sends messages storage to avoid duplicate exits
abstract contract BaseRootTunnel { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using SafeMath for uint256; DigitalaxAccessControls public accessControls; bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; IStateSender public stateSender; ICheckpointManager public checkpointManager; address public childTunnel; mapping(bytes32 => bool) public processedExits; constructor(DigitalaxAccessControls _accessControls, address _stateSender) public { accessControls = _accessControls; stateSender = IStateSender(_stateSender); } function setStateSender(address newStateSender) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setStateSender: Sender must have the admin role" ); stateSender = IStateSender(newStateSender); } function setCheckpointManager(address newCheckpointManager) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setCheckpointManager: Sender must have the admin role" ); checkpointManager = ICheckpointManager(newCheckpointManager); } function setChildTunnel(address newChildTunnel) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setChildTunnel: Sender must have the admin role" ); require(newChildTunnel != address(0x0), "RootTunnel: INVALID_CHILD_TUNNEL_ADDRESS"); childTunnel = newChildTunnel; } function _sendMessageToChild(bytes memory message) internal { stateSender.syncState(childTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); bytes32 exitHash = keccak256( abi.encodePacked( ) ); require( processedExits[exitHash] == false, "RootTunnel: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3] .toList()[ ]; RLPReader.RLPItem[] memory logRLPList = logRLP.toList(); require(childTunnel == RLPReader.toAddress(logRLPList[0]), "RootTunnel: INVALID_CHILD_TUNNEL"); require( MerklePatriciaProof.verify( ), "RootTunnel: INVALID_RECEIPT_PROOF" ); _checkBlockMembershipInCheckpoint( ); require( "RootTunnel: INVALID_SIGNATURE" ); bytes memory receivedData = logRLPList[2].toBytes(); return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootTunnel: INVALID_HEADER" ); return createdAt; } function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } }
520,372
[ 1, 79, 24410, 581, 5034, 12, 1079, 7828, 12, 3890, 3719, 919, 5793, 6835, 1365, 2687, 3301, 1151, 14825, 6835, 1492, 17024, 471, 9573, 2743, 2502, 358, 4543, 6751, 19526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 3360, 2375, 20329, 288, 203, 565, 1450, 534, 14461, 2514, 364, 1731, 31, 203, 565, 1450, 534, 14461, 2514, 364, 534, 14461, 2514, 18, 54, 48, 1102, 874, 31, 203, 565, 1450, 31827, 364, 1731, 1578, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 11678, 7053, 651, 16541, 87, 1071, 2006, 16795, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 31434, 67, 8723, 67, 10454, 67, 18513, 273, 374, 92, 28, 71, 25, 5558, 23553, 5292, 10525, 311, 3787, 5877, 6675, 2163, 72, 6260, 70, 378, 28, 74, 2643, 26, 72, 26, 24008, 3247, 27, 311, 1077, 22, 1727, 22, 73, 11149, 71, 27, 7201, 4033, 6028, 29, 70, 4630, 26, 31, 203, 203, 565, 467, 1119, 12021, 1071, 919, 12021, 31, 203, 565, 467, 14431, 1318, 1071, 9776, 1318, 31, 203, 565, 1758, 1071, 1151, 20329, 31, 203, 565, 2874, 12, 3890, 1578, 516, 1426, 13, 1071, 5204, 424, 1282, 31, 203, 203, 565, 3885, 12, 4907, 7053, 651, 16541, 87, 389, 3860, 16795, 16, 1758, 389, 2019, 12021, 13, 1071, 288, 203, 3639, 2006, 16795, 273, 389, 3860, 16795, 31, 203, 3639, 919, 12021, 273, 467, 1119, 12021, 24899, 2019, 12021, 1769, 203, 565, 289, 203, 203, 565, 445, 12947, 12021, 12, 2867, 15907, 12021, 13, 203, 565, 3903, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 2006, 16795, 18, 5332, 4446, 2996, 12, 3576, 18, 15330, 3631, 203, 5411, 315, 2171, 2375, 20329, 18, 542, 1119, 12021, 30, 15044, 1297, 1240, 326, 3981, 2478, 2 ]
./full_match/3/0x6C1E8b534f1611A1D767dadBc52270B5a8fb4baD/sources/D/prj/token-epan/time-locked-wallets/contracts/EPANTokenTimelockFactory.sol
Create new timelock. Add info. Send token from this transaction to the created contract. Emit event.
function newTimeLock(address _owner, uint256 _unlockDate, uint _tvalue) public returns(address) { require(_owner != address(0)); require(_owner != address(this)); require(_unlockDate > block.timestamp); require(_tvalue > 0); EPANTokenTimelock tlContract = new EPANTokenTimelock(token, _owner, _unlockDate); address timelock = address(tlContract); uint _contractBalance = contractBalance_(); require(token.transferFrom(msg.sender, address(this), _tvalue)); uint _value = contractBalance_().sub(_contractBalance); tlContracts.push(tlContract); tlContractsMapped[timelock] = tlContract; contracts[_owner].push(timelock); senders[_owner].push(msg.sender); beneficiaries.push(_owner); balances[_owner].push(_value); releaseTimes[_owner].push(_unlockDate); token.approve(timelock, _value); token.transfer(timelock, _value); Created(timelock, msg.sender, _owner, block.timestamp, _unlockDate, _value); contractsCount++; return (timelock); }
8,225,131
[ 1, 1684, 394, 1658, 292, 975, 18, 1436, 1123, 18, 2479, 1147, 628, 333, 2492, 358, 326, 2522, 6835, 18, 16008, 871, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 394, 950, 2531, 12, 2867, 389, 8443, 16, 2254, 5034, 389, 26226, 1626, 16, 2254, 389, 88, 1132, 13, 203, 3639, 1071, 203, 3639, 1135, 12, 2867, 13, 203, 565, 288, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 2211, 10019, 203, 3639, 2583, 24899, 26226, 1626, 405, 1203, 18, 5508, 1769, 203, 3639, 2583, 24899, 88, 1132, 405, 374, 1769, 203, 3639, 24067, 1258, 1345, 10178, 292, 975, 8332, 8924, 273, 394, 24067, 1258, 1345, 10178, 292, 975, 12, 2316, 16, 389, 8443, 16, 389, 26226, 1626, 1769, 203, 3639, 1758, 1658, 292, 975, 273, 1758, 12, 6172, 8924, 1769, 203, 540, 203, 3639, 2254, 389, 16351, 13937, 273, 6835, 13937, 67, 5621, 203, 3639, 2583, 12, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 88, 1132, 10019, 203, 3639, 2254, 389, 1132, 273, 6835, 13937, 67, 7675, 1717, 24899, 16351, 13937, 1769, 203, 540, 203, 3639, 8332, 20723, 18, 6206, 12, 6172, 8924, 1769, 203, 3639, 8332, 20723, 12868, 63, 8584, 292, 975, 65, 273, 8332, 8924, 31, 203, 3639, 20092, 63, 67, 8443, 8009, 6206, 12, 8584, 292, 975, 1769, 203, 3639, 1366, 414, 63, 67, 8443, 8009, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 27641, 74, 14463, 5646, 18, 6206, 24899, 8443, 1769, 203, 3639, 324, 26488, 63, 67, 8443, 8009, 6206, 24899, 1132, 1769, 203, 3639, 3992, 10694, 63, 67, 8443, 8009, 6206, 24899, 26226, 1626, 1769, 203, 203, 540, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-04-22 */ pragma solidity ^0.7.0; library DSMath { /// @dev github.com/makerdao/dss implementation /// of exponentiation by squaring //  nth power of x mod b function rpow(uint x, uint n, uint b) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := b} default {z := 0}} default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } } 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; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface 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 CompoundRateKeeper is Ownable { using SafeMath for uint256; struct CompoundRate { uint256 rate; uint256 lastUpdate; } CompoundRate public compoundRate; constructor () { compoundRate.rate = 1 * 10 ** 27; compoundRate.lastUpdate = block.timestamp; } function getCurrentRate() view external returns(uint256) { return compoundRate.rate; } function getLastUpdate() view external returns(uint256) { return compoundRate.lastUpdate; } function update(uint256 _interestRate) external onlyOwner returns(uint256) { uint256 _decimal = 10 ** 27; uint256 _period = (block.timestamp).sub(compoundRate.lastUpdate); uint256 _newRate = compoundRate.rate .mul(DSMath.rpow(_interestRate.add(_decimal), _period, _decimal)).div(_decimal); compoundRate.rate = _newRate; compoundRate.lastUpdate = block.timestamp; return _newRate; } } interface IEpanStaking { /** * @notice Update compound rate */ function updateCompoundRate() external; /** * @notice Update compound rate timeframe */ function updateCompoundRateTimeframe() external; /** * @notice Update both compound rates */ function updateCompoundRates() external; /** * @notice Update compound rate and stake tokens to user balance * @param _amount Amount to stake * @param _isTimeframe If true, stake to timeframe structure */ function updateCompoundAndStake(uint256 _amount, bool _isTimeframe) external returns (bool); /** * @notice Update compound rate and withdraw tokens from contract * @param _amount Amount to stake * @param _isTimeframe If true, withdraw from timeframe structure */ function updateCompoundAndWithdraw(uint256 _amount, bool _isTimeframe) external returns (bool); /** * @notice Stake tokens to user balance * @param _amount Amount to stake * @param _isTimeframe If true, stake to timeframe structure */ function stake(uint256 _amount, bool _isTimeframe) external returns (bool); /** * @notice Withdraw tokens from user balance. Only for timeframe stake * @param _amount Amount to withdraw * @param _isTimeframe If true, withdraws from timeframe structure */ function withdraw(uint256 _amount, bool _isTimeframe) external returns (bool); /** * @notice Returns the staking balance of the user * @param _isTimeframe If true, return balance from timeframe structure */ function getBalance(bool _isTimeframe) external view returns (uint256); /** * @notice Set interest rate */ function setInterestRate(uint256 _newInterestRate) external; /** * @notice Set interest rate timeframe * @param _newInterestRate New interest rate */ function setInterestRateTimeframe(uint256 _newInterestRate) external; /** * @notice Set interest rates * @param _newInterestRateTimeframe New interest rate timeframe */ function setInterestRates(uint256 _newInterestRate, uint256 _newInterestRateTimeframe) external; /** * @notice Add tokens to contract address to be spent as rewards * @param _amount Token amount that will be added to contract as reward */ function supplyRewardPool(uint256 _amount) external returns (bool); /** * @notice Get reward amount for sender address * @param _isTimeframe If timeframe, calculate reward for user from timeframe structure */ function getRewardAmount(bool _isTimeframe) external view returns (uint256); /** * @notice Get coefficient. Tokens on the contract / reward to be paid */ function monitorSecurityMargin() external view returns (uint256); } contract EpanStaking is IEpanStaking, Ownable { using SafeMath for uint; CompoundRateKeeper public compRateKeeper; CompoundRateKeeper public compRateKeeperTimeframe; IERC20 public epanToken; struct Stake { uint256 amount; uint256 normalizedAmount; } struct StakeTimeframe { uint256 amount; uint256 normalizedAmount; uint256 lastStakeTime; } uint256 public interestRate; uint256 public interestRateTimeframe; mapping(address => Stake) public userStakes; mapping(address => StakeTimeframe) public userStakesTimeframe; uint256 public aggregatedNormalizedStake; uint256 public aggregatedNormalizedStakeTimeframe; constructor(address _token, address _compRateKeeper, address _compRateKeeperTimeframe) { compRateKeeper = CompoundRateKeeper(_compRateKeeper); compRateKeeperTimeframe = CompoundRateKeeper(_compRateKeeperTimeframe); epanToken = IERC20(_token); } /** * @notice Update compound rate */ function updateCompoundRate() public override { compRateKeeper.update(interestRate); } /** * @notice Update compound rate timeframe */ function updateCompoundRateTimeframe() public override { compRateKeeperTimeframe.update(interestRateTimeframe); } /** * @notice Update both compound rates */ function updateCompoundRates() public override { updateCompoundRate(); updateCompoundRateTimeframe(); } /** * @notice Update compound rate and stake tokens to user balance * @param _amount Amount to stake * @param _isTimeframe If true, stake to timeframe structure */ function updateCompoundAndStake(uint256 _amount, bool _isTimeframe) external override returns (bool) { updateCompoundRates(); return stake(_amount, _isTimeframe); } /** * @notice Update compound rate and withdraw tokens from contract * @param _amount Amount to stake * @param _isTimeframe If true, withdraw from timeframe structure */ function updateCompoundAndWithdraw(uint256 _amount, bool _isTimeframe) external override returns (bool) { updateCompoundRates(); return withdraw(_amount, _isTimeframe); } /** * @notice Stake tokens to user balance * @param _amount Amount to stake * @param _isTimeframe If true, stake to timeframe structure */ function stake(uint256 _amount, bool _isTimeframe) public override returns (bool) { require(_amount > 0, "[E-11]-Invalid value for the stake amount, failed to stake a zero value."); if (_isTimeframe) { StakeTimeframe memory _stake = userStakesTimeframe[msg.sender]; uint256 _newAmount = _getBalance(_stake.normalizedAmount, true).add(_amount); uint256 _newNormalizedAmount = _newAmount.mul(10 ** 27).div(compRateKeeperTimeframe.getCurrentRate()); aggregatedNormalizedStakeTimeframe = aggregatedNormalizedStakeTimeframe.add(_newNormalizedAmount) .sub(_stake.normalizedAmount); userStakesTimeframe[msg.sender].amount = _stake.amount.add(_amount); userStakesTimeframe[msg.sender].normalizedAmount = _newNormalizedAmount; userStakesTimeframe[msg.sender].lastStakeTime = block.timestamp; } else { Stake memory _stake = userStakes[msg.sender]; uint256 _newAmount = _getBalance(_stake.normalizedAmount, false).add(_amount); uint256 _newNormalizedAmount = _newAmount.mul(10 ** 27).div(compRateKeeper.getCurrentRate()); aggregatedNormalizedStake = aggregatedNormalizedStake.add(_newNormalizedAmount) .sub(_stake.normalizedAmount); userStakes[msg.sender].amount = _stake.amount.add(_amount); userStakes[msg.sender].normalizedAmount = _newNormalizedAmount; } require(epanToken.transferFrom(msg.sender, address(this), _amount), "[E-12]-Failed to transfer token."); return true; } /** * @notice Withdraw tokens from user balance. Only for timeframe stake * @param _amount Amount to withdraw * @param _isTimeframe If true, withdraws from timeframe structure */ function withdraw(uint256 _amount, bool _isTimeframe) public override returns (bool) { uint256 _withdrawAmount = _amount; if (_isTimeframe) { StakeTimeframe memory _stake = userStakesTimeframe[msg.sender]; uint256 _userAmount = _getBalance(_stake.normalizedAmount, true); require(_userAmount != 0, "[E-31]-The deposit does not exist, failed to withdraw."); require(block.timestamp - _stake.lastStakeTime > 180 days, "[E-32]-Funds are not available for withdraw."); if (_userAmount < _withdrawAmount) _withdrawAmount = _userAmount; uint256 _newAmount = _userAmount.sub(_withdrawAmount); uint256 _newNormalizedAmount = _newAmount.mul(10 ** 27).div(compRateKeeperTimeframe.getCurrentRate()); aggregatedNormalizedStakeTimeframe = aggregatedNormalizedStakeTimeframe.add(_newNormalizedAmount) .sub(_stake.normalizedAmount); if (_withdrawAmount > _getRewardAmount(_stake.amount, _stake.normalizedAmount, _isTimeframe)) { userStakesTimeframe[msg.sender].amount = _newAmount; } userStakesTimeframe[msg.sender].normalizedAmount = _newNormalizedAmount; } else { Stake memory _stake = userStakes[msg.sender]; uint256 _userAmount = _getBalance(_stake.normalizedAmount, false); require(_userAmount != 0, "[E-33]-The deposit does not exist, failed to withdraw."); if (_userAmount < _withdrawAmount) _withdrawAmount = _userAmount; uint256 _newAmount = _getBalance(_stake.normalizedAmount, false).sub(_withdrawAmount); uint256 _newNormalizedAmount = _newAmount.mul(10 ** 27).div(compRateKeeper.getCurrentRate()); aggregatedNormalizedStake = aggregatedNormalizedStake.add(_newNormalizedAmount) .sub(_stake.normalizedAmount); if (_withdrawAmount > _getRewardAmount(_stake.amount, _stake.normalizedAmount, _isTimeframe)) { userStakes[msg.sender].amount = _newAmount; } userStakes[msg.sender].normalizedAmount = _newNormalizedAmount; } require(epanToken.transfer(msg.sender, _withdrawAmount), "[E-34]-Failed to transfer token."); return true; } /** * @notice Returns the staking balance of the user * @param _isTimeframe If true, return balance from timeframe structure */ function getBalance(bool _isTimeframe) public view override returns (uint256) { if (_isTimeframe) { return _getBalance(userStakesTimeframe[msg.sender].normalizedAmount, true); } return _getBalance(userStakes[msg.sender].normalizedAmount, false); } /** * @notice Returns the staking balance of the user * @param _normalizedAmount User normalized amount * @param _isTimeframe If true, return balance from timeframe structure */ function _getBalance(uint256 _normalizedAmount, bool _isTimeframe) private view returns (uint256) { if (_isTimeframe) { return _normalizedAmount.mul(compRateKeeperTimeframe.getCurrentRate()).div(10 ** 27); } return _normalizedAmount.mul(compRateKeeper.getCurrentRate()).div(10 ** 27); } /** * @notice Set interest rate */ function setInterestRate(uint256 _newInterestRate) external override onlyOwner { require(_newInterestRate <= 158548959918822932522, "[E-202]-Can't be more than 500%."); updateCompoundRate(); interestRate = _newInterestRate; } /** * @notice Set interest rate timeframe * @param _newInterestRate New interest rate */ function setInterestRateTimeframe(uint256 _newInterestRate) external override onlyOwner { require(_newInterestRate <= 158548959918822932522, "[E-211]-Can't be more than 500%."); updateCompoundRateTimeframe(); interestRateTimeframe = _newInterestRate; } /** * @notice Set interest rates * @param _newInterestRateTimeframe New interest rate timeframe */ function setInterestRates(uint256 _newInterestRate, uint256 _newInterestRateTimeframe) external override onlyOwner { require(_newInterestRate <= 158548959918822932522 && _newInterestRateTimeframe <= 158548959918822932522, "[E-221]-Can't be more than 500%."); updateCompoundRate(); updateCompoundRateTimeframe(); interestRate = _newInterestRate; interestRateTimeframe = _newInterestRateTimeframe; } /** * @notice Add tokens to contract address to be spent as rewards * @param _amount Token amount that will be added to contract as reward */ function supplyRewardPool(uint256 _amount) external override onlyOwner returns (bool) { require(epanToken.transferFrom(msg.sender, address(this), _amount), "[E-231]-Failed to transfer token."); return true; } /** * @notice Get reward amount for sender address * @param _isTimeframe If timeframe, calculate reward for user from timeframe structure */ function getRewardAmount(bool _isTimeframe) external view override returns (uint256) { if (_isTimeframe) { StakeTimeframe memory _stake = userStakesTimeframe[msg.sender]; return _getRewardAmount(_stake.amount, _stake.normalizedAmount, true); } Stake memory _stake = userStakes[msg.sender]; return _getRewardAmount(_stake.amount, _stake.normalizedAmount, false); } /** * @notice Get reward amount by params * @param _amount Token amount * @param _normalizedAmount Normalized token amount * @param _isTimeframe If timeframe, calculate reward for user from timeframe structure */ function _getRewardAmount(uint256 _amount, uint256 _normalizedAmount, bool _isTimeframe) private view returns (uint256) { uint256 _balance = 0; if (_isTimeframe) { _balance = _getBalance(_normalizedAmount, _isTimeframe); } else { _balance = _getBalance(_normalizedAmount, _isTimeframe); } if (_balance <= _amount) return 0; return _balance.sub(_amount); } /** * @notice Get coefficient. Tokens on the contract / total stake + total reward to be paid */ function monitorSecurityMargin() external view override onlyOwner returns (uint256) { uint256 _contractBalance = epanToken.balanceOf(address(this)); uint256 _toReward = aggregatedNormalizedStake.mul(compRateKeeper.getCurrentRate()).div(10 ** 27); uint256 _toRewardTimeframe = aggregatedNormalizedStakeTimeframe.mul(compRateKeeperTimeframe.getCurrentRate()) .div(10 ** 27); return _contractBalance.mul(10 ** 27).div(_toReward.add(_toRewardTimeframe)); } }
* @notice Set interest rate/
function setInterestRate(uint256 _newInterestRate) external override onlyOwner { require(_newInterestRate <= 158548959918822932522, "[E-202]-Can't be more than 500%."); updateCompoundRate(); interestRate = _newInterestRate; }
2,251,248
[ 1, 694, 16513, 4993, 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, 565, 445, 444, 29281, 4727, 12, 11890, 5034, 389, 2704, 29281, 4727, 13, 3903, 3849, 1338, 5541, 288, 203, 3639, 2583, 24899, 2704, 29281, 4727, 1648, 4711, 28, 6564, 6675, 25, 2733, 2643, 24532, 29, 1578, 25, 3787, 16, 5158, 41, 17, 18212, 65, 17, 2568, 1404, 506, 1898, 2353, 6604, 9, 1199, 1769, 203, 540, 203, 3639, 1089, 16835, 4727, 5621, 203, 3639, 16513, 4727, 273, 389, 2704, 29281, 4727, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./interfaces/IUniswapV2Router02.sol"; import "./libraries/SafeMath.sol"; import "./libraries/SafeERC20.sol"; import "./libraries/ReentrancyGuard.sol"; contract Multiswap is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Ownership change pending address private pendingOwner; // WETH Address address private immutable WETH; // Uniswap Router for swaps IUniswapV2Router02 private immutable uniswapRouter; // Referral data mapping (address => bool) private referrers; mapping (address => uint256) private referralFees; // Data struct struct ContractData { uint160 owner; uint16 swapFeeBase; uint16 swapFeeToken; uint16 referralFee; uint16 maxFee; } ContractData private data; // Modifier for only owner functions modifier onlyOwner { require(msg.sender == address(data.owner), "Not allowed"); _; } /** * @dev Constructor sets values for Uniswap, WETH, and fee data * * These values are the immutable state values for Uniswap and WETH. * */ constructor(address _router, address _weth) { uniswapRouter = IUniswapV2Router02(_router); WETH = _weth; data.owner = uint160(msg.sender); // add extra two digits to percent for accuracy (30 = 0.3) data.swapFeeBase = uint16(30); // 0.3% data.swapFeeToken = uint16(20); // 0.2% per token data.referralFee = uint16(4500); // 45% for referrals data.maxFee = uint16(150); // 1.5% max fee // Add standard referrers referrers[address(this)] = true; referrers[address(0x1190074795DAD0E61b61270De48e108427f8f817)] = true; } /** * @dev Receive ETH */ receive() external payable {} fallback() external payable {} /** * @dev Checks and returns expected output fom ETH swap. */ function checkOutputsETH( address[] memory _tokens, uint256[] memory _percent, uint256[] memory _slippage, uint256 _total ) external view returns (address[] memory, uint256[] memory, uint256) { require(_tokens.length == _percent.length && _percent.length == _slippage.length, 'Multiswap: mismatch input data'); uint256 _totalPercent; (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(_total, _tokens.length); uint256[] memory _outputAmount = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { _totalPercent += _percent[i]; (_outputAmount[i],) = calcOutputEth( _tokens[i], valueToSend.mul(_percent[i]).div(100), _slippage[i] ); } require(_totalPercent == 100, 'Multiswap: portfolio not 100%'); return (_tokens, _outputAmount, feeAmount); } /** * @dev Checks and returns expected output from token swap. */ function checkOutputsToken( address[] memory _tokens, uint256[] memory _percent, uint256[] memory _slippage, address _base, uint256 _total ) external view returns (address[] memory, uint256[] memory) { require(_tokens.length == _percent.length && _percent.length == _slippage.length, 'Multiswap: mismatch input data'); uint256 _totalPercent; uint256[] memory _outputAmount = new uint256[](_tokens.length); address[] memory path = new address[](3); path[0] = _base; path[1] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { _totalPercent += _percent[i]; path[2] = _tokens[i]; uint256[] memory expected = uniswapRouter.getAmountsOut(_total.mul(_percent[i]).div(100), path); uint256 adjusted = expected[2].sub(expected[2].mul(_slippage[i]).div(1000)); _outputAmount[i] = adjusted; } require(_totalPercent == 100, 'Multiswap: portolio not 100%'); return (_tokens, _outputAmount); } /** * @dev Checks and returns ETH value of token amount. */ function checkTokenValueETH(address _token, uint256 _amount, uint256 _slippage) public view returns (uint256) { address[] memory path = new address[](2); path[0] = _token; path[1] = WETH; uint256[] memory expected = uniswapRouter.getAmountsOut(_amount, path); uint256 adjusted = expected[1].sub(expected[1].mul(_slippage).div(1000)); return adjusted; } /** * @dev Checks and returns ETH value of portfolio. */ function checkAllValue(address[] memory _tokens, uint256[] memory _amounts, uint256[] memory _slippage) external view returns (uint256) { uint256 totalValue; for (uint i = 0; i < _tokens.length; i++) { totalValue += checkTokenValueETH(_tokens[i], _amounts[i], _slippage[i]); } return totalValue; } /** * @dev Internal function to calculate the output from one ETH swap. */ function calcOutputEth(address _token, uint256 _value, uint256 _slippage) internal view returns (uint256, address[] memory) { address[] memory path = new address[](2); path[0] = WETH; path[1] = _token; uint256[] memory expected = uniswapRouter.getAmountsOut(_value, path); uint256 adjusted = expected[1].sub(expected[1].mul(_slippage).div(1000)); return (adjusted, path); } /** * @dev Internal function to calculate the output from one token swap. */ function calcOutputToken(address[] memory _path, uint256 _value) internal view returns (uint256[] memory expected) { expected = uniswapRouter.getAmountsOut(_value, _path); return expected; } /** * @dev Execute ETH swap for each token in portfolio. */ function makeETHSwap(address[] memory _tokens, uint256[] memory _percent, uint256[] memory _expected, address _referrer) external payable nonReentrant { require(address(0) != _referrer, 'Multiswap: referrer cannot be zero addresss'); require(_tokens.length == _percent.length && _percent.length == _expected.length, 'Multiswap: Input data mismatch'); (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(msg.value, _tokens.length); uint256 totalPercent; address[] memory path = new address[](2); path[0] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { totalPercent += _percent[i]; require(totalPercent <= 100, 'Multiswap: Exceeded 100%'); path[1] = _tokens[i]; uint256 swapVal = valueToSend.mul(_percent[i]).div(100); uniswapRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: swapVal}( _expected[i], path, msg.sender, block.timestamp + 1200 ); } require(totalPercent == 100, 'Multiswap: Percent not 100'); if (_referrer != address(this)) { uint256 referralFee = takeReferralFee(feeAmount, _referrer); (bool sent, ) = _referrer.call{value: referralFee}(""); require(sent, 'Multiswap: Failed to send referral fee'); } } /** * @dev Execute token swap for each token in portfolio. */ function makeTokenSwap( address[] memory _tokens, uint256[] memory _percent, uint256[] memory _expected, address _referrer, address _base, uint256 _total) external nonReentrant { require(address(0) != _referrer, 'Multiswap: referrer cannot be zero addresss'); require(_tokens.length == _percent.length && _percent.length == _expected.length, 'Multiswap: Input data mismatch'); uint256 totalToSend = receiveToken(_total, _base, true); uint256 totalPercent = 0; address[] memory path = new address[](3); path[0] = _base; path[1] = WETH; for (uint256 i = 0; i < _tokens.length; i++) { totalPercent += _percent[i]; require(totalPercent <= 100, 'Multiswap: Exceeded 100'); path[2] = _tokens[i]; uint256 swapVal = totalToSend.mul(_percent[i]).div(100); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( swapVal, _expected[i], path, msg.sender, block.timestamp + 1200 ); } require(totalPercent == 100, 'Multiswap: Percent not 100'); } /** * @dev Receive token and handle any logic required for reflection tokens */ function receiveToken(uint256 _amount, address _token, bool _toSend) internal returns (uint256 amountReceived) { IERC20 token = IERC20(_token); uint256 preBalanceToken = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); if (_amount > token.balanceOf(address(this)).sub(preBalanceToken)) { amountReceived = token.balanceOf(address(this)).sub(preBalanceToken); } else { amountReceived = _amount; } if (_toSend) require(token.approve(address(uniswapRouter), amountReceived), 'Multiswap: Uniswap approval failed'); return amountReceived; } /** * @dev Swap tokens for ETH */ function makeTokenSwapForETH( address[] memory _tokens, uint256[] memory _amounts, uint256[] memory _expected, address _referrer ) external nonReentrant { require(address(0) != _referrer, 'Multiswap: referrer cannot be zero addresss'); require(_tokens.length == _amounts.length && _expected.length == _expected.length, 'Multiswap: Input data mismatch'); address[] memory path = new address[](2); path[1] = WETH; uint256 preBalance = address(this).balance; for (uint i = 0; i < _tokens.length; i++) { path[0] = _tokens[i]; uint256 totalToSend = receiveToken(_amounts[i], _tokens[i], true); uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(totalToSend, _expected[i], path, address(this), block.timestamp + 1200); } (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(address(this).balance.sub(preBalance), _tokens.length); if (_referrer != address(this)) { uint256 referralFee = takeReferralFee(feeAmount, _referrer); (bool sent, ) = _referrer.call{value: referralFee}(""); require(sent, 'Multiswap: Failed to send referral fee'); } (bool delivered, ) = msg.sender.call{value: valueToSend}(""); require(delivered, 'Multiswap: Failed to send swap output'); } /** * @dev Apply fee to total value amount for ETH swap. */ function applyFeeETH(uint256 _amount, uint256 _numberOfTokens) private view returns (uint256 valueToSend, uint256 feeAmount) { uint256 feePercent = _numberOfTokens.mul(data.swapFeeToken); feePercent -= data.swapFeeToken; feePercent += data.swapFeeBase; if (feePercent > data.maxFee) { feePercent = data.maxFee; } feeAmount = _amount.mul(feePercent).div(10000); valueToSend = _amount.sub(feeAmount); return (valueToSend, feeAmount); } /** * @dev Take referral fee and distribute */ function takeReferralFee(uint256 _fee, address _referrer) internal returns (uint256) { require(referrers[_referrer], 'Multiswap: Not signed up as referrer'); uint256 referralFee = _fee.mul(data.referralFee).div(10000); referralFees[_referrer] = referralFees[_referrer].add(referralFee); return referralFee; } /** * @dev Owner only function to update contract fees. */ function updateFee( uint16 _newFeeBase, uint16 _newFeeToken, uint16 _newFeeReferral, uint16 _newMaxFee ) external onlyOwner returns (bool) { data.swapFeeBase = _newFeeBase; data.swapFeeToken = _newFeeToken; data.referralFee = _newFeeReferral; data.maxFee = _newMaxFee; return true; } /** * @dev Returns current app fees. */ function getCurrentFee() external view returns ( uint16, uint16, uint16, uint16 ) { return (data.swapFeeBase, data.swapFeeToken, data.referralFee, data.maxFee); } /** * @dev Owner only function to change contract owner. */ function transferOwnership(address _newOwner) external onlyOwner returns (bool) { require(address(0) != _newOwner, "Multiswap: newOwner set to the zero address"); pendingOwner = _newOwner; return true; } /** * @dev Function to claim ownership as pending owner. */ function claimOwnership() external { require(msg.sender == pendingOwner, 'Multiswap: not pending owner'); data.owner = uint160(pendingOwner); pendingOwner = address(0); } /** * @dev Owner only function to renounce ownership. */ function renounceOwnership() external onlyOwner { pendingOwner = address(0); data.owner = uint160(0); } /** * @dev Owner only function to change contract owner. */ function addReferrer(address _referrer) external onlyOwner returns (bool) { referrers[_referrer] = true; return true; } /** * @dev Owner only function to change contract owner. */ function removeReferrer(address _referrer) external onlyOwner returns (bool) { referrers[_referrer] = false; return true; } /** * @dev Return owner address */ function getOwner() external view returns (address) { return address(data.owner); } /** * @dev Function to see referral balances */ function getReferralFees(address _referrer) external view returns (uint256) { return referralFees[_referrer]; } /** * @dev Owner only function to retreive ETH fees */ function retrieveEthFees() external onlyOwner { (bool sent, ) = address(data.owner).call{value: address(this).balance}(""); require(sent, 'Multiswap: Transfer failed'); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @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: Unlicensed pragma solidity 0.8.7; interface IUniswapV2Router02 { function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @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 pragma solidity 0.8.7; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' 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.7; 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; } }
* @dev Swap tokens for ETH/
function makeTokenSwapForETH( address[] memory _tokens, uint256[] memory _amounts, uint256[] memory _expected, address _referrer ) external nonReentrant { require(address(0) != _referrer, 'Multiswap: referrer cannot be zero addresss'); require(_tokens.length == _amounts.length && _expected.length == _expected.length, 'Multiswap: Input data mismatch'); address[] memory path = new address[](2); path[1] = WETH; uint256 preBalance = address(this).balance; for (uint i = 0; i < _tokens.length; i++) { path[0] = _tokens[i]; uint256 totalToSend = receiveToken(_amounts[i], _tokens[i], true); uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(totalToSend, _expected[i], path, address(this), block.timestamp + 1200); } (uint256 valueToSend, uint256 feeAmount) = applyFeeETH(address(this).balance.sub(preBalance), _tokens.length); if (_referrer != address(this)) { uint256 referralFee = takeReferralFee(feeAmount, _referrer); require(sent, 'Multiswap: Failed to send referral fee'); } require(delivered, 'Multiswap: Failed to send swap output'); }
13,644,425
[ 1, 12521, 2430, 364, 512, 2455, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1221, 1345, 12521, 1290, 1584, 44, 12, 203, 3639, 1758, 8526, 3778, 389, 7860, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 8949, 87, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 3825, 16, 203, 3639, 1758, 389, 1734, 11110, 203, 565, 262, 3903, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 2583, 12, 2867, 12, 20, 13, 480, 389, 1734, 11110, 16, 296, 5049, 291, 91, 438, 30, 14502, 2780, 506, 3634, 1758, 87, 8284, 203, 3639, 2583, 24899, 7860, 18, 2469, 422, 389, 8949, 87, 18, 2469, 597, 389, 3825, 18, 2469, 422, 389, 3825, 18, 2469, 16, 296, 5049, 291, 91, 438, 30, 2741, 501, 13484, 8284, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 21, 65, 273, 678, 1584, 44, 31, 203, 3639, 2254, 5034, 675, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 540, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 7860, 18, 2469, 31, 277, 27245, 288, 203, 5411, 589, 63, 20, 65, 273, 389, 7860, 63, 77, 15533, 203, 5411, 2254, 5034, 2078, 28878, 273, 6798, 1345, 24899, 8949, 87, 63, 77, 6487, 389, 7860, 63, 77, 6487, 638, 1769, 203, 5411, 640, 291, 91, 438, 8259, 18, 22270, 14332, 5157, 1290, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 4963, 28878, 16, 389, 3825, 63, 77, 6487, 589, 16, 1758, 12, 2211, 3631, 1203, 18, 5508, 397, 2593, 713, 1769, 203, 3639, 289, 203, 203, 3639, 261, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge * * Implementation of an example of a diamond. /******************************************************************************/ import "./OwnershipFacet.sol"; import "./DiamondStorageContract.sol"; import "./DiamondHeaders.sol"; import "./DiamondFacet.sol"; import "./DiamondLoupeFacet.sol"; contract Diamond is IERC173Events, IERC165, DiamondStorageContract, DiamondFacet { constructor(address owner) payable { DiamondStorage storage ds = diamondStorage(); ds.contractOwner = owner; emit OwnershipTransferred(address(0), owner); // Create a DiamondFacet contract which implements the Diamond interface DiamondFacet diamondFacet = new DiamondFacet(); // Create a DiamondLoupeFacet contract which implements the Diamond Loupe interface DiamondLoupeFacet diamondLoupeFacet = new DiamondLoupeFacet(); // Create a OwnershipFacet contract which implements the ERC-173 Ownership interface OwnershipFacet ownershipFacet = new OwnershipFacet(); bytes[] memory cut = new bytes[](4); // Adding cut function cut[0] = abi.encodePacked( diamondFacet, IDiamond.diamondCut.selector ); // Adding diamond loupe functions cut[1] = abi.encodePacked( diamondLoupeFacet, IDiamondLoupe.facetFunctionSelectors.selector, IDiamondLoupe.facets.selector, IDiamondLoupe.facetAddress.selector, IDiamondLoupe.facetAddresses.selector ); // Adding diamond ERC173 functions cut[2] = abi.encodePacked( ownershipFacet, IERC173.transferOwnership.selector, IERC173.owner.selector ); // Adding supportsInterface function cut[3] = abi.encodePacked(address(this), IERC165.supportsInterface.selector); // execute non-standard internal diamondCut function to add functions diamondCut(cut); // adding ERC165 data // ERC165 ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; // DiamondCut ds.supportedInterfaces[IDiamond.diamondCut.selector] = true; // DiamondLoupe bytes4 interfaceID = IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector; ds.supportedInterfaces[interfaceID] = true; // ERC173 ds.supportedInterfaces[IERC173.transferOwnership.selector ^ IERC173.owner.selector] = true; } // This is an immutable functions because it is defined directly in the diamond. // Why is it here instead of in a facet? No reason, just to show an immutable function. // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external override view returns (bool) { DiamondStorage storage ds = diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { DiamondStorage storage ds; bytes32 position = DiamondStorageContract.DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } address facet = address(bytes20(ds.facets[msg.sig])); require(facet != address(0)); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } receive() external payable {} // Non-standard internal function version of diamondCut // This code is exaclty the same as externalCut in DiamondFacet, except it allows anyone to call it (internally) and is using // 'bytes[] memory _diamondCut' instead of 'bytes[] calldata _diamondCut' // The code is duplicated to prevent copying calldata to memory which // causes an error for an array of bytes arrays. function diamondCut(bytes[] memory _diamondCut) internal { DiamondStorage storage ds = diamondStorage(); SlotInfo memory slot; slot.originalSelectorSlotsLength = ds.selectorSlotsLength; uint selectorSlotsLength = uint128(slot.originalSelectorSlotsLength); uint selectorSlotLength = uint128(slot.originalSelectorSlotsLength >> 128); if(selectorSlotLength > 0) { slot.selectorSlot = ds.selectorSlots[selectorSlotsLength]; } // loop through diamond cut for(uint diamondCutIndex; diamondCutIndex < _diamondCut.length; diamondCutIndex++) { bytes memory facetCut = _diamondCut[diamondCutIndex]; require(facetCut.length > 20, "Missing facet or selector info."); bytes32 currentSlot; assembly { currentSlot := mload(add(facetCut,32)) } bytes32 newFacet = bytes20(currentSlot); uint numSelectors = (facetCut.length - 20) / 4; uint position = 52; // adding or replacing functions if(newFacet != 0) { // add and replace selectors for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++) { bytes4 selector; assembly { selector := mload(add(facetCut,position)) } position += 4; bytes32 oldFacet = ds.facets[selector]; // add if(oldFacet == 0) { // update the last slot at then end of the function slot.updateLastSlot = true; ds.facets[selector] = newFacet | bytes32(selectorSlotLength) << 64 | bytes32(selectorSlotsLength); // clear selector position in slot and add selector slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorSlotLength * 32) | bytes32(selector) >> selectorSlotLength * 32; selectorSlotLength++; // if slot is full then write it to storage if(selectorSlotLength == 8) { ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot; slot.selectorSlot = 0; selectorSlotLength = 0; selectorSlotsLength++; } } // replace else { require(bytes20(oldFacet) != bytes20(newFacet), "Function cut to same facet."); // replace old facet address ds.facets[selector] = oldFacet & CLEAR_ADDRESS_MASK | newFacet; } } } // remove functions else { slot.updateLastSlot = true; for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++) { bytes4 selector; assembly { selector := mload(add(facetCut,position)) } position += 4; bytes32 oldFacet = ds.facets[selector]; require(oldFacet != 0, "Function doesn't exist. Can't remove."); // Current slot is empty so get the slot before it if(slot.selectorSlot == 0) { selectorSlotsLength--; slot.selectorSlot = ds.selectorSlots[selectorSlotsLength]; selectorSlotLength = 8; } slot.oldSelectorSlotsIndex = uint64(uint(oldFacet)); slot.oldSelectorSlotIndex = uint32(uint(oldFacet >> 64)); // gets the last selector in the slot bytes4 lastSelector = bytes4(slot.selectorSlot << (selectorSlotLength-1) * 32); if(slot.oldSelectorSlotsIndex != selectorSlotsLength) { slot.oldSelectorSlot = ds.selectorSlots[slot.oldSelectorSlotsIndex]; // clears the selector we are deleting and puts the last selector in its place. slot.oldSelectorSlot = slot.oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32; // update storage with the modified slot ds.selectorSlots[slot.oldSelectorSlotsIndex] = slot.oldSelectorSlot; selectorSlotLength--; } else { // clears the selector we are deleting and puts the last selector in its place. slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32; selectorSlotLength--; } if(selectorSlotLength == 0) { delete ds.selectorSlots[selectorSlotsLength]; slot.selectorSlot = 0; } if(lastSelector != selector) { // update last selector slot position info ds.facets[lastSelector] = oldFacet & CLEAR_ADDRESS_MASK | bytes20(ds.facets[lastSelector]); } delete ds.facets[selector]; } } } uint newSelectorSlotsLength = selectorSlotLength << 128 | selectorSlotsLength; if(newSelectorSlotsLength != slot.originalSelectorSlotsLength) { ds.selectorSlotsLength = newSelectorSlotsLength; } if(slot.updateLastSlot && selectorSlotLength > 0) { ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot; } emit DiamondCut(_diamondCut, address(0), new bytes(0)); } }
Non-standard internal function version of diamondCut This code is exaclty the same as externalCut in DiamondFacet, except it allows anyone to call it (internally) and is using 'bytes[] memory _diamondCut' instead of 'bytes[] calldata _diamondCut' The code is duplicated to prevent copying calldata to memory which causes an error for an array of bytes arrays. loop through diamond cut adding or replacing functions add and replace selectors add update the last slot at then end of the function clear selector position in slot and add selector if slot is full then write it to storage replace replace old facet address remove functions Current slot is empty so get the slot before it clears the selector we are deleting and puts the last selector in its place. update storage with the modified slot clears the selector we are deleting and puts the last selector in its place. update last selector slot position info
function diamondCut(bytes[] memory _diamondCut) internal { DiamondStorage storage ds = diamondStorage(); SlotInfo memory slot; slot.originalSelectorSlotsLength = ds.selectorSlotsLength; uint selectorSlotsLength = uint128(slot.originalSelectorSlotsLength); uint selectorSlotLength = uint128(slot.originalSelectorSlotsLength >> 128); if(selectorSlotLength > 0) { slot.selectorSlot = ds.selectorSlots[selectorSlotsLength]; } for(uint diamondCutIndex; diamondCutIndex < _diamondCut.length; diamondCutIndex++) { bytes memory facetCut = _diamondCut[diamondCutIndex]; require(facetCut.length > 20, "Missing facet or selector info."); bytes32 currentSlot; assembly { currentSlot := mload(add(facetCut,32)) } bytes32 newFacet = bytes20(currentSlot); uint numSelectors = (facetCut.length - 20) / 4; uint position = 52; if(newFacet != 0) { for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++) { bytes4 selector; assembly { selector := mload(add(facetCut,position)) } position += 4; bytes32 oldFacet = ds.facets[selector]; if(oldFacet == 0) { slot.updateLastSlot = true; ds.facets[selector] = newFacet | bytes32(selectorSlotLength) << 64 | bytes32(selectorSlotsLength); slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorSlotLength * 32) | bytes32(selector) >> selectorSlotLength * 32; selectorSlotLength++; if(selectorSlotLength == 8) { ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot; slot.selectorSlot = 0; selectorSlotLength = 0; selectorSlotsLength++; } } else { require(bytes20(oldFacet) != bytes20(newFacet), "Function cut to same facet."); ds.facets[selector] = oldFacet & CLEAR_ADDRESS_MASK | newFacet; } } } else { slot.updateLastSlot = true; for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++) { bytes4 selector; assembly { selector := mload(add(facetCut,position)) } position += 4; bytes32 oldFacet = ds.facets[selector]; require(oldFacet != 0, "Function doesn't exist. Can't remove."); if(slot.selectorSlot == 0) { selectorSlotsLength--; slot.selectorSlot = ds.selectorSlots[selectorSlotsLength]; selectorSlotLength = 8; } slot.oldSelectorSlotsIndex = uint64(uint(oldFacet)); slot.oldSelectorSlotIndex = uint32(uint(oldFacet >> 64)); if(slot.oldSelectorSlotsIndex != selectorSlotsLength) { slot.oldSelectorSlot = ds.selectorSlots[slot.oldSelectorSlotsIndex]; slot.oldSelectorSlot = slot.oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32; ds.selectorSlots[slot.oldSelectorSlotsIndex] = slot.oldSelectorSlot; selectorSlotLength--; } else { slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32; selectorSlotLength--; } if(selectorSlotLength == 0) { delete ds.selectorSlots[selectorSlotsLength]; slot.selectorSlot = 0; } if(lastSelector != selector) { ds.facets[lastSelector] = oldFacet & CLEAR_ADDRESS_MASK | bytes20(ds.facets[lastSelector]); } delete ds.facets[selector]; } } } uint newSelectorSlotsLength = selectorSlotLength << 128 | selectorSlotsLength; if(newSelectorSlotsLength != slot.originalSelectorSlotsLength) { ds.selectorSlotsLength = newSelectorSlotsLength; } if(slot.updateLastSlot && selectorSlotLength > 0) { ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot; } emit DiamondCut(_diamondCut, address(0), new bytes(0)); }
12,718,829
[ 1, 3989, 17, 10005, 2713, 445, 1177, 434, 4314, 301, 1434, 15812, 1220, 981, 353, 431, 10150, 4098, 326, 1967, 487, 3903, 15812, 316, 12508, 301, 1434, 11137, 16, 1335, 518, 5360, 1281, 476, 358, 745, 518, 261, 267, 798, 1230, 13, 471, 353, 1450, 296, 3890, 8526, 3778, 389, 3211, 301, 1434, 15812, 11, 3560, 434, 296, 3890, 8526, 745, 892, 389, 3211, 301, 1434, 15812, 11, 1021, 981, 353, 16975, 358, 5309, 8933, 745, 892, 358, 3778, 1492, 14119, 392, 555, 364, 392, 526, 434, 1731, 5352, 18, 2798, 3059, 4314, 301, 1434, 6391, 6534, 578, 13993, 4186, 527, 471, 1453, 11424, 527, 1089, 326, 1142, 4694, 622, 1508, 679, 434, 326, 445, 2424, 3451, 1754, 316, 4694, 471, 527, 3451, 309, 4694, 353, 1983, 1508, 1045, 518, 358, 2502, 1453, 1453, 1592, 11082, 1758, 1206, 4186, 6562, 4694, 353, 1008, 1427, 336, 326, 4694, 1865, 518, 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, 4314, 301, 1434, 15812, 12, 3890, 8526, 3778, 389, 3211, 301, 1434, 15812, 13, 2713, 288, 203, 3639, 12508, 301, 1434, 3245, 2502, 3780, 273, 4314, 301, 1434, 3245, 5621, 203, 3639, 23195, 966, 3778, 4694, 31, 203, 3639, 4694, 18, 8830, 4320, 16266, 1782, 273, 3780, 18, 9663, 16266, 1782, 31, 203, 3639, 2254, 3451, 16266, 1782, 273, 2254, 10392, 12, 14194, 18, 8830, 4320, 16266, 1782, 1769, 203, 3639, 2254, 3451, 8764, 1782, 273, 2254, 10392, 12, 14194, 18, 8830, 4320, 16266, 1782, 1671, 8038, 1769, 203, 3639, 309, 12, 9663, 8764, 1782, 405, 374, 13, 288, 203, 5411, 4694, 18, 9663, 8764, 273, 3780, 18, 9663, 16266, 63, 9663, 16266, 1782, 15533, 203, 3639, 289, 203, 3639, 364, 12, 11890, 4314, 301, 1434, 15812, 1016, 31, 4314, 301, 1434, 15812, 1016, 411, 389, 3211, 301, 1434, 15812, 18, 2469, 31, 4314, 301, 1434, 15812, 1016, 27245, 288, 203, 5411, 1731, 3778, 11082, 15812, 273, 389, 3211, 301, 1434, 15812, 63, 3211, 301, 1434, 15812, 1016, 15533, 203, 5411, 2583, 12, 21568, 15812, 18, 2469, 405, 4200, 16, 315, 4841, 11082, 578, 3451, 1123, 1199, 1769, 203, 5411, 1731, 1578, 783, 8764, 31, 203, 5411, 19931, 288, 203, 7734, 783, 8764, 519, 312, 945, 12, 1289, 12, 21568, 15812, 16, 1578, 3719, 203, 5411, 289, 203, 5411, 1731, 1578, 394, 11137, 273, 1731, 3462, 12, 2972, 8764, 1769, 203, 5411, 2254, 818, 19277, 273, 261, 21568, 15812, 18, 2469, 300, 4200, 13, 342, 1059, 31, 203, 5411, 2254, 1754, 273, 2 ]
./full_match/80001/0xA360355db783C0Ff155885F846386588CF220CA8/sources/src/interfaces/ISignatureMintWithParams.sol
* The 'signature minting' mechanism used in thirdweb Token smart contracts is a way for a contract admin to authorize an external party's request to mint tokens on the admin's contract. At a high level, this means you can authorize some external party to mint tokens on your contract, and specify what exactly will be minted by that external party./
interface ISignatureMintWithParams { pragma solidity ^0.8.0; struct BaseRequest { uint128 validityStartTimestamp; uint128 validityEndTimestamp; bytes32 uid; } }
5,643,270
[ 1, 1986, 296, 8195, 312, 474, 310, 11, 12860, 1399, 316, 12126, 4875, 3155, 13706, 20092, 353, 279, 4031, 364, 279, 6835, 3981, 358, 12229, 392, 3903, 18285, 1807, 225, 590, 358, 312, 474, 2430, 603, 326, 3981, 1807, 6835, 18, 225, 2380, 279, 3551, 1801, 16, 333, 4696, 1846, 848, 12229, 2690, 3903, 18285, 358, 312, 474, 2430, 603, 3433, 6835, 16, 471, 4800, 4121, 8950, 903, 506, 225, 312, 474, 329, 635, 716, 3903, 18285, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 5374, 49, 474, 19591, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 1958, 3360, 691, 288, 203, 3639, 2254, 10392, 13800, 1685, 4921, 31, 203, 3639, 2254, 10392, 13800, 1638, 4921, 31, 203, 3639, 1731, 1578, 4555, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xe229084e0892f26a2Eec44349C36463F4b93E5c6/sources/contracts/TransactionManager.sol
* @notice Sets the timestamp for an owner to be proposed, and sets the newly proposed owner as step 1 in a 2-step process/
function proposeNewOwner(address newlyProposed) public virtual onlyOwner { _setProposed(newlyProposed); }
8,344,442
[ 1, 2785, 326, 2858, 364, 392, 3410, 358, 506, 20084, 16, 471, 1678, 326, 10894, 20084, 3410, 487, 2235, 404, 316, 279, 576, 17, 4119, 1207, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 450, 4150, 1908, 5541, 12, 2867, 10894, 626, 7423, 13, 1071, 5024, 1338, 5541, 288, 203, 565, 389, 542, 626, 7423, 12, 2704, 715, 626, 7423, 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 ]
./partial_match/1/0x57a204AA1042f6E66DD7730813f4024114d74f37/sources/Kongz.sol
making sure the ID fits the opensea format: first 20 bytes are the maker address next 7 bytes are the nft ID last 5 bytes the value associated to the ID, here will always be equal to 1 There will only be 1000 kongz, we can fix boundaries and remove 5 ids that dont match kongz
function isValidKong(uint256 _id) pure internal returns(bool) { if (_id >> 96 != 0x000000000000000000000000a2548e7ad6cee01eeb19d49bedb359aea3d8ad1d) return false; if (_id & 0x000000000000000000000000000000000000000000000000000000ffffffffff != 1) return false; uint256 id = (_id & 0x0000000000000000000000000000000000000000ffffffffffffff0000000000) >> 40; if (id > 1005 || id == 262 || id == 197 || id == 75 || id == 34 || id == 18 || id == 0) return false; return true; }
2,702,958
[ 1, 19718, 3071, 326, 1599, 13351, 326, 1696, 307, 69, 740, 30, 1122, 4200, 1731, 854, 326, 312, 6388, 1758, 1024, 2371, 1731, 854, 326, 290, 1222, 1599, 1142, 1381, 1731, 326, 460, 3627, 358, 326, 1599, 16, 2674, 903, 3712, 506, 3959, 358, 404, 6149, 903, 1338, 506, 4336, 417, 932, 94, 16, 732, 848, 2917, 15054, 471, 1206, 1381, 3258, 716, 14046, 845, 417, 932, 94, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 4908, 47, 932, 12, 11890, 5034, 389, 350, 13, 16618, 2713, 1135, 12, 6430, 13, 288, 203, 202, 202, 430, 261, 67, 350, 1671, 19332, 480, 374, 92, 12648, 12648, 12648, 69, 2947, 8875, 73, 27, 361, 26, 311, 73, 1611, 1340, 70, 3657, 72, 7616, 2992, 70, 4763, 29, 8906, 69, 23, 72, 28, 361, 21, 72, 13, 203, 1082, 202, 2463, 629, 31, 203, 202, 202, 430, 261, 67, 350, 473, 374, 92, 12648, 12648, 12648, 12648, 12648, 12648, 9449, 9460, 18217, 480, 404, 13, 203, 1082, 202, 2463, 629, 31, 203, 202, 202, 11890, 5034, 612, 273, 261, 67, 350, 473, 374, 92, 12648, 12648, 12648, 12648, 12648, 9460, 9460, 18217, 2787, 9449, 13, 1671, 8063, 31, 203, 202, 202, 430, 261, 350, 405, 2130, 25, 747, 612, 422, 576, 8898, 747, 612, 422, 24527, 747, 612, 422, 18821, 747, 612, 422, 13438, 747, 612, 422, 6549, 747, 612, 422, 374, 13, 203, 1082, 202, 2463, 629, 31, 203, 202, 202, 2463, 638, 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 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IBondCalculator { function markdown( address _LP ) external view returns ( uint ); function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ); function claim ( address _recipient ) external returns ( uint ); function forfeit() external returns ( uint ); function toggleLock() external; function unstake( uint _amount, bool _trigger ) external returns ( uint ); function rebase() external; function index() external view returns ( uint ); function contractBalance() external view returns ( uint ); function totalStaked() external view returns ( uint ); function supplyInWarmup() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( uint ); function withdraw( uint _amount, address _token ) external; function valueOfToken( address _token, uint _amount ) external view returns ( uint value_ ); function mint( address _recipient, uint _amount ) external; function mintRewards( address _recipient, uint _amount ) external; function incurDebt( uint amount_, address token_ ) external; function repayDebtWithReserve( uint amount_, address token_ ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; import "./FullMath.sol"; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMathExtended { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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 sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(a, b, "SafeMath: subtraction overflow"); } function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 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 mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 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; } 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IsKEEPER is IERC20 { function rebase( uint256 profit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function balanceOf(address who) external override view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IwTROVE is IERC20 { function wrap(uint _amount) external returns (uint); function unwrap(uint _amount) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/SafeMathExtended.sol"; contract StakingDistributor is Ownable { using SafeERC20 for IERC20; using SafeMathExtended for uint256; using SafeMathExtended for uint32; IERC20 immutable KEEPER; ITreasury immutable treasury; uint32 public immutable epochLength; uint32 public nextEpochTime; mapping( uint => Adjust ) public adjustments; /* ====== STRUCTS ====== */ struct Info { uint rate; // in ten-thousandths ( 5000 = 0.5% ) address recipient; } Info[] public info; struct Adjust { bool add; uint rate; uint target; } constructor( address _treasury, address _KEEPER, uint32 _epochLength, uint32 _nextEpochTime ) { require( _treasury != address(0) ); treasury = ITreasury( _treasury ); require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); epochLength = _epochLength; nextEpochTime = _nextEpochTime; } /** @notice send epoch reward to staking contract */ function distribute() external returns (bool) { if ( nextEpochTime <= uint32(block.timestamp) ) { nextEpochTime = nextEpochTime.add32( epochLength ); // set next epoch block // distribute rewards to each recipient for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].rate > 0 ) { treasury.mintRewards( // mint and send from treasury info[ i ].recipient, nextRewardAt( info[ i ].rate ) ); adjust( i ); // check for adjustment } } return true; } else { return false; } } /** @notice increment reward rate for collector */ function adjust( uint _index ) internal { Adjust memory adjustment = adjustments[ _index ]; if ( adjustment.rate != 0 ) { if ( adjustment.add ) { // if rate should increase info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate if ( info[ _index ].rate >= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } else { // if rate should decrease info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate if ( info[ _index ].rate <= adjustment.target || info[ _index ].rate < adjustment.rate) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } } } /* ====== VIEW FUNCTIONS ====== */ /** @notice view function for next reward at given rate @param _rate uint @return uint */ function nextRewardAt( uint _rate ) public view returns ( uint ) { return KEEPER.totalSupply().mul( _rate ).div( 1000000 ); } /** @notice view function for next reward for specified address @param _recipient address @return uint */ function nextRewardFor( address _recipient ) public view returns ( uint ) { uint reward; for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].recipient == _recipient ) { reward = nextRewardAt( info[ i ].rate ); } } return reward; } /* ====== POLICY FUNCTIONS ====== */ /** @notice adds recipient for distributions @param _recipient address @param _rewardRate uint */ function addRecipient( address _recipient, uint _rewardRate ) external onlyOwner() { require( _recipient != address(0) ); info.push( Info({ recipient: _recipient, rate: _rewardRate })); } /** @notice removes recipient for distributions @param _index uint @param _recipient address */ function removeRecipient( uint _index, address _recipient ) external onlyOwner() { require( _recipient == info[ _index ].recipient ); info[ _index ] = info[info.length-1]; info.pop(); } /** @notice set adjustment info for a collector's reward rate @param _index uint @param _add bool @param _rate uint @param _target uint */ function setAdjustment( uint _index, bool _add, uint _rate, uint _target ) external onlyOwner() { require(_add || info[ _index ].rate >= _rate, "Negative adjustment rate cannot be more than current rate."); adjustments[ _index ] = Adjust({ add: _add, rate: _rate, target: _target }); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; contract oldTreasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event Deposit( address indexed token, uint amount, uint value ); event Withdrawal( address indexed token, uint amount, uint value ); event CreateDebt( address indexed debtor, address indexed token, uint amount, uint value ); event RepayDebt( address indexed debtor, address indexed token, uint amount, uint value ); event ReservesManaged( address indexed token, uint amount ); event ReservesUpdated( uint indexed totalReserves ); event ReservesAudited( uint indexed totalReserves ); event RewardsMinted( address indexed caller, address indexed recipient, uint amount ); event ChangeQueued( MANAGING indexed managing, address queued ); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SKEEPER } IKeplerERC20 immutable KEEPER; uint public immutable secondsNeededForQueue; uint public constant keeperDecimals = 9; address[] public reserveTokens; // Push only, beware false-positives. mapping( address => bool ) public isReserveToken; mapping( address => uint ) public reserveTokenQueue; // Delays changes to mapping. address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveDepositor; mapping( address => uint ) public reserveDepositorQueue; // Delays changes to mapping. address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveSpender; mapping( address => uint ) public reserveSpenderQueue; // Delays changes to mapping. address[] public liquidityTokens; // Push only, beware false-positives. mapping( address => bool ) public isLiquidityToken; mapping( address => uint ) public LiquidityTokenQueue; // Delays changes to mapping. address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isLiquidityDepositor; mapping( address => uint ) public LiquidityDepositorQueue; // Delays changes to mapping. mapping( address => address ) public bondCalculator; // bond calculator for liquidity token address[] public reserveManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveManager; mapping( address => uint ) public ReserveManagerQueue; // Delays changes to mapping. address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isLiquidityManager; mapping( address => uint ) public LiquidityManagerQueue; // Delays changes to mapping. address[] public debtors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isDebtor; mapping( address => uint ) public debtorQueue; // Delays changes to mapping. mapping( address => uint ) public debtorBalance; address[] public rewardManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isRewardManager; mapping( address => uint ) public rewardManagerQueue; // Delays changes to mapping. address public sKEEPER; uint public sKEEPERQueue; // Delays change to sKEEPER address uint public totalReserves; // Risk-free value of all assets uint public totalDebt; constructor (address _KEEPER, address _USDC, address _DAI, uint _secondsNeededForQueue) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); // isLiquidityToken[ _KEEPERDAI ] = true; // liquidityTokens.push( _KEEPERDAI ); secondsNeededForQueue = _secondsNeededForQueue; } /** @notice allow approved address to deposit an asset for KEEPER @param _amount uint @param _token address @param _profit uint @return send_ uint */ function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); if ( isReserveToken[ _token ] ) { require( isReserveDepositor[ msg.sender ], "Not approved" ); } else { require( isLiquidityDepositor[ msg.sender ], "Not approved" ); } uint value = valueOfToken(_token, _amount); // mint KEEPER needed and store amount of rewards for distribution send_ = value.sub( _profit ); KEEPER.mint( msg.sender, send_ ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } /** @notice allow approved address to burn KEEPER for reserves @param _amount uint @param _token address */ function withdraw( uint _amount, address _token ) external { require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions require( isReserveSpender[ msg.sender ] == true, "Not approved" ); uint value = valueOfToken( _token, _amount ); KEEPER.burnFrom( msg.sender, value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); emit Withdrawal( _token, _amount, value ); } /** @notice allow approved address to borrow reserves @param _amount uint @param _token address */ function incurDebt( uint _amount, address _token ) external { require( isDebtor[ msg.sender ], "Not approved" ); require( isReserveToken[ _token ], "Not accepted" ); uint value = valueOfToken( _token, _amount ); uint maximumDebt = IERC20Extended( sKEEPER ).balanceOf( msg.sender ); // Can only borrow against sKEEPER held uint availableDebt = maximumDebt.sub( debtorBalance[ msg.sender ] ); require( value <= availableDebt, "Exceeds debt limit" ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].add( value ); totalDebt = totalDebt.add( value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).transfer( msg.sender, _amount ); emit CreateDebt( msg.sender, _token, _amount, value ); } /** @notice allow approved address to repay borrowed reserves with reserves @param _amount uint @param _token address */ function repayDebtWithReserve( uint _amount, address _token ) external { require( isDebtor[ msg.sender ], "Not approved" ); require( isReserveToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken( _token, _amount ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( value ); totalDebt = totalDebt.sub( value ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit RepayDebt( msg.sender, _token, _amount, value ); } /** @notice allow approved address to repay borrowed reserves with KEEPER @param _amount uint */ function repayDebtWithKEEPER( uint _amount ) external { require( isDebtor[ msg.sender ], "Not approved" ); KEEPER.burnFrom( msg.sender, _amount ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount ); totalDebt = totalDebt.sub( _amount ); emit RepayDebt( msg.sender, address(KEEPER), _amount, _amount ); } /** @notice allow approved address to withdraw assets @param _token address @param _amount uint */ function manage( address _token, uint _amount ) external { if( isLiquidityToken[ _token ] ) { require( isLiquidityManager[ msg.sender ], "Not approved" ); } else { require( isReserveManager[ msg.sender ], "Not approved" ); } uint value = valueOfToken(_token, _amount); require( value <= excessReserves(), "Insufficient reserves" ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); emit ReservesManaged( _token, _amount ); } /** @notice send epoch reward to staking contract */ function mintRewards( address _recipient, uint _amount ) external { require( isRewardManager[ msg.sender ], "Not approved" ); require( _amount <= excessReserves(), "Insufficient reserves" ); KEEPER.mint( _recipient, _amount ); emit RewardsMinted( msg.sender, _recipient, _amount ); } /** @notice returns excess reserves not backing tokens @return uint */ function excessReserves() public view returns ( uint ) { return totalReserves.sub( KEEPER.totalSupply().sub( totalDebt ) ); } /** @notice takes inventory of all tracked assets @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyOwner() { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } totalReserves = reserves; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() ); } else if ( isLiquidityToken[ _token ] ) { value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount ); } } /** @notice queue address to change boolean in mapping @param _managing MANAGING @param _address address @return bool */ function queue( MANAGING _managing, address _address ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0 reserveDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVESPENDER ) { // 1 reserveSpenderQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVETOKEN ) { // 2 reserveTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3 ReserveManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4 LiquidityDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5 LiquidityTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6 LiquidityManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.DEBTOR ) { // 7 debtorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.REWARDMANAGER ) { // 8 rewardManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.SKEEPER ) { // 9 sKEEPERQueue = block.timestamp.add( secondsNeededForQueue ); } else return false; emit ChangeQueued( _managing, _address ); return true; } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculator address @return bool */ function toggle( MANAGING _managing, address _address, address _calculator ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); bool result; if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0 if ( requirements( reserveDepositorQueue, isReserveDepositor, _address ) ) { reserveDepositorQueue[ _address ] = 0; if( !listContains( reserveDepositors, _address ) ) { reserveDepositors.push( _address ); } } result = !isReserveDepositor[ _address ]; isReserveDepositor[ _address ] = result; } else if ( _managing == MANAGING.RESERVESPENDER ) { // 1 if ( requirements( reserveSpenderQueue, isReserveSpender, _address ) ) { reserveSpenderQueue[ _address ] = 0; if( !listContains( reserveSpenders, _address ) ) { reserveSpenders.push( _address ); } } result = !isReserveSpender[ _address ]; isReserveSpender[ _address ] = result; } else if ( _managing == MANAGING.RESERVETOKEN ) { // 2 if ( requirements( reserveTokenQueue, isReserveToken, _address ) ) { reserveTokenQueue[ _address ] = 0; if( !listContains( reserveTokens, _address ) ) { reserveTokens.push( _address ); } } result = !isReserveToken[ _address ]; isReserveToken[ _address ] = result; } else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3 if ( requirements( ReserveManagerQueue, isReserveManager, _address ) ) { reserveManagers.push( _address ); ReserveManagerQueue[ _address ] = 0; if( !listContains( reserveManagers, _address ) ) { reserveManagers.push( _address ); } } result = !isReserveManager[ _address ]; isReserveManager[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4 if ( requirements( LiquidityDepositorQueue, isLiquidityDepositor, _address ) ) { liquidityDepositors.push( _address ); LiquidityDepositorQueue[ _address ] = 0; if( !listContains( liquidityDepositors, _address ) ) { liquidityDepositors.push( _address ); } } result = !isLiquidityDepositor[ _address ]; isLiquidityDepositor[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5 if ( requirements( LiquidityTokenQueue, isLiquidityToken, _address ) ) { LiquidityTokenQueue[ _address ] = 0; if( !listContains( liquidityTokens, _address ) ) { liquidityTokens.push( _address ); } } result = !isLiquidityToken[ _address ]; isLiquidityToken[ _address ] = result; bondCalculator[ _address ] = _calculator; } else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6 if ( requirements( LiquidityManagerQueue, isLiquidityManager, _address ) ) { LiquidityManagerQueue[ _address ] = 0; if( !listContains( liquidityManagers, _address ) ) { liquidityManagers.push( _address ); } } result = !isLiquidityManager[ _address ]; isLiquidityManager[ _address ] = result; } else if ( _managing == MANAGING.DEBTOR ) { // 7 if ( requirements( debtorQueue, isDebtor, _address ) ) { debtorQueue[ _address ] = 0; if( !listContains( debtors, _address ) ) { debtors.push( _address ); } } result = !isDebtor[ _address ]; isDebtor[ _address ] = result; } else if ( _managing == MANAGING.REWARDMANAGER ) { // 8 if ( requirements( rewardManagerQueue, isRewardManager, _address ) ) { rewardManagerQueue[ _address ] = 0; if( !listContains( rewardManagers, _address ) ) { rewardManagers.push( _address ); } } result = !isRewardManager[ _address ]; isRewardManager[ _address ] = result; } else if ( _managing == MANAGING.SKEEPER ) { // 9 sKEEPERQueue = 0; sKEEPER = _address; result = true; } else return false; emit ChangeActivated( _managing, _address, result ); return true; } /** @notice checks requirements and returns altered structs @param queue_ mapping( address => uint ) @param status_ mapping( address => bool ) @param _address address @return bool */ function requirements( mapping( address => uint ) storage queue_, mapping( address => bool ) storage status_, address _address ) internal view returns ( bool ) { if ( !status_[ _address ] ) { require( queue_[ _address ] != 0, "Must queue" ); require( queue_[ _address ] <= block.timestamp, "Queue not expired" ); return true; } return false; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains( address[] storage _list, address _token ) internal view returns ( bool ) { for( uint i = 0; i < _list.length; i++ ) { if( _list[ i ] == _token ) { return true; } } return false; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256 amount_) external; function mint(address account_, uint256 ammount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./interfaces/IStaking.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract StakingHelper { address public immutable staking; address public immutable KEEPER; constructor ( address _staking, address _KEEPER ) { require( _staking != address(0) ); staking = _staking; require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function stake( uint _amount, bool _wrap ) external { IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, msg.sender, _wrap ); IStaking( staking ).claim( msg.sender ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IDistributor.sol"; import "./interfaces/IiKEEPER.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./libraries/SafeMathExtended.sol"; contract oldStaking is Ownable { using SafeERC20 for IERC20; using SafeERC20 for IsKEEPER; using SafeMathExtended for uint256; using SafeMathExtended for uint32; event DistributorSet( address distributor ); event WarmupSet( uint warmup ); event IKeeperSet( address iKEEPER ); struct Epoch { uint32 length; uint32 endTime; uint32 number; uint distribute; } struct Claim { uint deposit; uint gons; uint expiry; bool lock; // prevents malicious delays } IERC20 public immutable KEEPER; IsKEEPER public immutable sKEEPER; IwTROVE public immutable wTROVE; Epoch public epoch; address public distributor; address public iKEEPER; mapping( address => Claim ) public warmupInfo; uint32 public warmupPeriod; uint gonsInWarmup; constructor (address _KEEPER, address _sKEEPER, address _wTROVE, uint32 _epochLength, uint32 _firstEpochNumber, uint32 _firstEpochTime) { require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); require( _sKEEPER != address(0) ); sKEEPER = IsKEEPER( _sKEEPER ); require( _wTROVE != address(0) ); wTROVE = IwTROVE( _wTROVE ); epoch = Epoch({ length: _epochLength, number: _firstEpochNumber, endTime: _firstEpochTime, distribute: 0 }); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice stake KEEPER to enter warmup * @param _amount uint * @param _recipient address */ function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ) { rebase(); KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); if ( warmupPeriod == 0 ) { return _send( _recipient, _amount, _wrap ); } else { Claim memory info = warmupInfo[ _recipient ]; if ( !info.lock ) { require( _recipient == msg.sender, "External deposits for account are locked" ); } uint sKeeperGons = sKEEPER.gonsForBalance( _amount ); warmupInfo[ _recipient ] = Claim ({ deposit: info.deposit.add(_amount), gons: info.gons.add(sKeeperGons), expiry: epoch.number.add32(warmupPeriod), lock: info.lock }); gonsInWarmup = gonsInWarmup.add(sKeeperGons); return _amount; } } function stakeInvest( uint _stakeAmount, uint _investAmount, address _recipient, bool _wrap ) external { rebase(); uint keeperAmount = _stakeAmount.add(_investAmount.div(1e9)); KEEPER.safeTransferFrom( msg.sender, address(this), keeperAmount ); _send( _recipient, _stakeAmount, _wrap ); sKEEPER.approve(iKEEPER, _investAmount); IiKEEPER(iKEEPER).wrap(_investAmount, _recipient); } /** * @notice retrieve stake from warmup * @param _recipient address */ function claim ( address _recipient ) public returns ( uint ) { Claim memory info = warmupInfo[ _recipient ]; if ( epoch.number >= info.expiry && info.expiry != 0 ) { delete warmupInfo[ _recipient ]; gonsInWarmup = gonsInWarmup.sub(info.gons); return _send( _recipient, sKEEPER.balanceForGons( info.gons ), false); } return 0; } /** * @notice forfeit stake and retrieve KEEPER */ function forfeit() external returns ( uint ) { Claim memory info = warmupInfo[ msg.sender ]; delete warmupInfo[ msg.sender ]; gonsInWarmup = gonsInWarmup.sub(info.gons); KEEPER.safeTransfer( msg.sender, info.deposit ); return info.deposit; } /** * @notice prevent new deposits or claims from ext. address (protection from malicious activity) */ function toggleLock() external { warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock; } /** * @notice redeem sKEEPER for KEEPER * @param _amount uint * @param _trigger bool */ function unstake( uint _amount, bool _trigger ) external returns ( uint ) { if ( _trigger ) { rebase(); } uint amount = _amount; sKEEPER.safeTransferFrom( msg.sender, address(this), _amount ); KEEPER.safeTransfer( msg.sender, amount ); return amount; } /** @notice trigger rebase if epoch over */ function rebase() public { if( epoch.endTime <= uint32(block.timestamp) ) { sKEEPER.rebase( epoch.distribute, epoch.number ); epoch.endTime = epoch.endTime.add32(epoch.length); epoch.number++; if ( distributor != address(0) ) { IDistributor( distributor ).distribute(); } uint contractBalanceVal = contractBalance(); uint totalStakedVal = totalStaked(); if( contractBalanceVal <= totalStakedVal ) { epoch.distribute = 0; } else { epoch.distribute = contractBalanceVal.sub(totalStakedVal); } } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice send staker their amount as sKEEPER or gKEEPER * @param _recipient address * @param _amount uint */ function _send( address _recipient, uint _amount, bool _wrap ) internal returns ( uint ) { if (_wrap) { sKEEPER.approve( address( wTROVE ), _amount ); uint wrapValue = wTROVE.wrap( _amount ); wTROVE.transfer( _recipient, wrapValue ); } else { sKEEPER.safeTransfer( _recipient, _amount ); // send as sKEEPER (equal unit as KEEPER) } return _amount; } /* ========== VIEW FUNCTIONS ========== */ /** @notice returns the sKEEPER index, which tracks rebase growth @return uint */ function index() public view returns ( uint ) { return sKEEPER.index(); } /** @notice returns contract KEEPER holdings, including bonuses provided @return uint */ function contractBalance() public view returns ( uint ) { return KEEPER.balanceOf( address(this) ); } function totalStaked() public view returns ( uint ) { return sKEEPER.circulatingSupply(); } function supplyInWarmup() public view returns ( uint ) { return sKEEPER.balanceForGons( gonsInWarmup ); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** @notice sets the contract address for LP staking @param _address address */ function setDistributor( address _address ) external onlyOwner() { distributor = _address; emit DistributorSet( _address ); } /** * @notice set warmup period for new stakers * @param _warmupPeriod uint */ function setWarmup( uint32 _warmupPeriod ) external onlyOwner() { warmupPeriod = _warmupPeriod; emit WarmupSet( _warmupPeriod ); } function setIKeeper( address _iKEEPER ) external onlyOwner() { iKEEPER = _iKEEPER; emit IKeeperSet( _iKEEPER ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IDistributor { function distribute() external returns ( bool ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IiKEEPER is IERC20 { function wrap(uint _amount, address _recipient) external; function unwrap(uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; contract wTROVE is ERC20 { using SafeMath for uint; address public immutable TROVE; constructor(address _TROVE) ERC20("Wrapped Trove", "wTROVE") { require(_TROVE != address(0)); TROVE = _TROVE; } /** @notice wrap TROVE @param _amount uint @return uint */ function wrap( uint _amount ) external returns ( uint ) { IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); uint value = TROVETowTROVE( _amount ); _mint( msg.sender, value ); return value; } /** @notice unwrap TROVE @param _amount uint @return uint */ function unwrap( uint _amount ) external returns ( uint ) { _burn( msg.sender, _amount ); uint value = wTROVEToTROVE( _amount ); IsKEEPER( TROVE ).transfer( msg.sender, value ); return value; } /** @notice converts wTROVE amount to TROVE @param _amount uint @return uint */ function wTROVEToTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( IsKEEPER( TROVE ).index() ).div( 10 ** decimals() ); } /** @notice converts TROVE amount to wTROVE @param _amount uint @return uint */ function TROVETowTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( 10 ** decimals() ).div( IsKEEPER( TROVE ).index() ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract USDC is ERC20, Ownable { using SafeMath for uint256; constructor() ERC20("USDC", "USDC") { } function mint(address account_, uint256 amount_) external onlyOwner() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/IStaking.sol"; contract sKeplerERC20 is ERC20 { using SafeMath for uint256; event StakingContractUpdated(address stakingContract); event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply); event LogRebase(uint256 indexed epoch, uint256 rebase, uint256 index); address initializer; address public stakingContract; // balance used to calc rebase uint8 private constant _tokenDecimals = 9; uint INDEX; // Index Gons - tracks rebase growth uint _totalSupply; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**_tokenDecimals; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping (address => mapping (address => uint256)) private _allowedValue; struct Rebase { uint epoch; uint rebase; // 18 decimals uint totalStakedBefore; uint totalStakedAfter; uint amountRebased; uint index; uint timeOccured; } Rebase[] public rebases; // past rebase data modifier onlyStakingContract() { require(msg.sender == stakingContract); _; } constructor() ERC20("Staked Keeper", "TROVE") { _setupDecimals(_tokenDecimals); initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function setIndex(uint _INDEX) external { require(msg.sender == initializer); require(INDEX == 0); require(_INDEX != 0); INDEX = gonsForBalance(_INDEX); } // do this last function initialize(address _stakingContract) external { require(msg.sender == initializer); require(_stakingContract != address(0)); stakingContract = _stakingContract; _gonBalances[ stakingContract ] = TOTAL_GONS; emit Transfer(address(0x0), stakingContract, _totalSupply); emit StakingContractUpdated(_stakingContract); initializer = address(0); } /** @notice increases sKEEPER supply to increase staking balances relative to _profit @param _profit uint256 @return uint256 */ function rebase(uint256 _profit, uint _epoch) public onlyStakingContract() returns (uint256) { uint256 rebaseAmount; uint256 _circulatingSupply = circulatingSupply(); if (_profit == 0) { emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, 0, index()); return _totalSupply; } else if (_circulatingSupply > 0) { rebaseAmount = _profit.mul(_totalSupply).div(_circulatingSupply); } else { rebaseAmount = _profit; } _totalSupply = _totalSupply.add(rebaseAmount); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); _storeRebase(_circulatingSupply, _profit, _epoch); return _totalSupply; } /** @notice emits event with data about rebase @param _previousCirculating uint @param _profit uint @param _epoch uint @return bool */ function _storeRebase(uint _previousCirculating, uint _profit, uint _epoch) internal returns (bool) { uint rebasePercent = _profit.mul(1e18).div(_previousCirculating); rebases.push(Rebase ({ epoch: _epoch, rebase: rebasePercent, // 18 decimals totalStakedBefore: _previousCirculating, totalStakedAfter: circulatingSupply(), amountRebased: _profit, index: index(), timeOccured: uint32(block.timestamp) })); emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, rebasePercent, index()); return true; } /* =================================== VIEW FUNCTIONS ========================== */ /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[ who ].div(_gonsPerFragment); } /** * @param who The address to query. * @return The gon balance of the specified address. */ function scaledBalanceOf(address who) external view returns (uint256) { return _gonBalances[who]; } function gonsForBalance(uint amount) public view returns (uint) { return amount * _gonsPerFragment; } function balanceForGons(uint gons) public view returns (uint) { return gons / _gonsPerFragment; } // Staking contract holds excess sKEEPER function circulatingSupply() public view returns (uint) { return _totalSupply.sub(balanceOf(stakingContract)).add(IStaking(stakingContract).supplyInWarmup()); } function index() public view returns (uint) { return balanceForGons(INDEX); } function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedValue[ owner_ ][ spender ]; } /* ================================= MUTATIVE FUNCTIONS ====================== */ function transfer(address to, uint256 value) public override returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub(gonValue); _gonBalances[ to ] = _gonBalances[ to ].add(gonValue); emit Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public override returns (bool) { _allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub(value); emit Approval(from, msg.sender, _allowedValue[ from ][ msg.sender ]); uint256 gonValue = gonsForBalance(value); _gonBalances[ from ] = _gonBalances[from].sub(gonValue); _gonBalances[ to ] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } function _approve(address owner, address spender, uint256 value) internal override virtual { _allowedValue[owner][spender] = value; emit Approval(owner, spender, value); } function approve(address spender, uint256 value) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add(addedValue); emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedValue[ msg.sender ][ spender ]; if (subtractedValue >= oldValue) { _allowedValue[ msg.sender ][ spender ] = 0; } else { _allowedValue[ msg.sender ][ spender ] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract cKEEPER is ERC20, Ownable { using SafeMath for uint; bool public requireSellerApproval; mapping( address => bool ) public isApprovedSeller; constructor() ERC20("Call Keeper", "cKEEPER") { uint initSupply = 500000000 * 1e18; _addApprovedSeller( address(this) ); _addApprovedSeller( msg.sender ); _mint( msg.sender, initSupply ); requireSellerApproval = true; } function allowOpenTrading() external onlyOwner() returns ( bool ) { requireSellerApproval = false; return requireSellerApproval; } function _addApprovedSeller( address approvedSeller_ ) internal { isApprovedSeller[approvedSeller_] = true; } function addApprovedSeller( address approvedSeller_ ) external onlyOwner() returns ( bool ) { _addApprovedSeller( approvedSeller_ ); return isApprovedSeller[approvedSeller_]; } function addApprovedSellers( address[] calldata approvedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < approvedSellers_.length; iteration_++ ) { _addApprovedSeller( approvedSellers_[iteration_] ); } return true; } function _removeApprovedSeller( address disapprovedSeller_ ) internal { isApprovedSeller[disapprovedSeller_] = false; } function removeApprovedSeller( address disapprovedSeller_ ) external onlyOwner() returns ( bool ) { _removeApprovedSeller( disapprovedSeller_ ); return isApprovedSeller[disapprovedSeller_]; } function removeApprovedSellers( address[] calldata disapprovedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < disapprovedSellers_.length; iteration_++ ) { _removeApprovedSeller( disapprovedSellers_[iteration_] ); } return true; } function _beforeTokenTransfer(address from_, address to_, uint256 amount_ ) internal override { require( (balanceOf(to_) > 0 || isApprovedSeller[from_] == true || !requireSellerApproval), "Account not approved to transfer cKEEPER." ); } function burn(uint256 amount_) public virtual { _burn( msg.sender, amount_ ); } function burnFrom( address account_, uint256 amount_ ) public virtual { _burnFrom( account_, amount_ ); } function _burnFrom( address account_, uint256 amount_ ) internal virtual { uint256 decreasedAllowance_ = allowance( account_, msg.sender ).sub( amount_, "ERC20: burn amount exceeds allowance"); _approve( account_, msg.sender, decreasedAllowance_ ); _burn( account_, amount_ ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; interface IBond { function redeem( address _recipient, bool _stake ) external returns ( uint ); function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ); } contract RedeemHelper is Ownable { address[] public bonds; function redeemAll( address _recipient, bool _stake ) external { for( uint i = 0; i < bonds.length; i++ ) { if ( bonds[i] != address(0) ) { if ( IBond( bonds[i] ).pendingPayoutFor( _recipient ) > 0 ) { IBond( bonds[i] ).redeem( _recipient, _stake ); } } } } function addBondContract( address _bond ) external onlyOwner() { require( _bond != address(0) ); bonds.push( _bond ); } function removeBondContract( uint _index ) external onlyOwner() { bonds[ _index ] = address(0); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract KEEPERCircSupply is Ownable { using SafeMath for uint; address public KEEPER; address[] public nonCirculatingKEEPERAddresses; constructor (address _KEEPER) { KEEPER = _KEEPER; } function KEEPERCirculatingSupply() external view returns (uint) { uint _totalSupply = IERC20( KEEPER ).totalSupply(); uint _circulatingSupply = _totalSupply.sub( getNonCirculatingKEEPER() ); return _circulatingSupply; } function getNonCirculatingKEEPER() public view returns ( uint ) { uint _nonCirculatingKEEPER; for( uint i=0; i < nonCirculatingKEEPERAddresses.length; i = i.add( 1 ) ) { _nonCirculatingKEEPER = _nonCirculatingKEEPER.add( IERC20( KEEPER ).balanceOf( nonCirculatingKEEPERAddresses[i] ) ); } return _nonCirculatingKEEPER; } function setNonCirculatingKEEPERAddresses( address[] calldata _nonCirculatingAddresses ) external onlyOwner() returns ( bool ) { nonCirculatingKEEPERAddresses = _nonCirculatingAddresses; return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/ITreasury.sol"; import "../interfaces/IStaking.sol"; interface IcKEEPER { function burnFrom( address account_, uint256 amount_ ) external; } contract cKeeperExercise is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; address public immutable cKEEPER; address public immutable KEEPER; address public immutable USDC; address public immutable treasury; address public staking; uint private constant CLIFF = 250000 * 10**9; // Minimum KEEPER supply to exercise uint private constant TOUCHDOWN = 5000000 * 10**9; // Maximum KEEPER supply for percent increase uint private constant Y_INCREASE = 35000; // Increase from CLIFF to TOUCHDOWN is 3.5%. 4 decimals used // uint private constant SLOPE = Y_INCREASE.div(TOUCHDOWN.sub(CLIFF)); // m = (y2 - y1) / (x2 - x1) struct Term { uint initPercent; // 4 decimals ( 5000 = 0.5% ) uint claimed; uint max; } mapping(address => Term) public terms; mapping(address => address) public walletChange; constructor( address _cKEEPER, address _KEEPER, address _USDC, address _treasury, address _staking ) { require( _cKEEPER != address(0) ); cKEEPER = _cKEEPER; require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _USDC != address(0) ); USDC = _USDC; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; } function setStaking( address _staking ) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } // Sets terms for a new wallet function setTerms(address _vester, uint _amountCanClaim, uint _rate ) external onlyOwner() returns ( bool ) { terms[_vester].max = _amountCanClaim; terms[_vester].initPercent = _rate; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].max = _amountCanClaims[i]; terms[_vesters[i]].initPercent = _rates[i]; } return true; } // Allows wallet to redeem cKEEPER for KEEPER function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' ); uint usdcAmount = _amount.div(1e12); IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount ); IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount ); IERC20( USDC ).approve( treasury, usdcAmount ); uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 ); terms[ msg.sender ].claimed = info.claimed.add( _amount ); if ( _stake ) { IERC20( KEEPER ).approve( staking, KEEPERToSend ); IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap ); } else { IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend ); } return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].initPercent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem based on current supply function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { if ( _info.initPercent == 0 ) { return 0; } uint keeperSupply = IERC20( KEEPER ).totalSupply(); if (keeperSupply < CLIFF) { return 0; } else if (keeperSupply > TOUCHDOWN) { keeperSupply = TOUCHDOWN; } uint percent = Y_INCREASE.mul(keeperSupply.sub(CLIFF)).div(TOUCHDOWN.sub(CLIFF)).add(_info.initPercent); return ( keeperSupply.mul( percent ).mul( 1000 ) ).sub( _info.claimed ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake2 is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } // function withdrawaKeeper() external { // require(block.timestamp > withdrawStart, "Not started."); // uint amount = depositInfo[msg.sender].mul(110).div(100); // require(amount > 0, "No deposit present."); // delete depositInfo[msg.sender]; // aKEEPER.transfer(msg.sender, amount); // } function migrate() external { require(block.timestamp > withdrawStart, "Not started."); require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require(block.timestamp > withdrawStart, "Not started."); require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } function withdrawaKeeper() external { require(block.timestamp > withdrawStart, "Not started."); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; aKEEPER.transfer(msg.sender, amount); } function migrate() external { require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract oldaKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; event KeeperRedeemed(address tokenOwner, uint256 amount); event TroveRedeemed(address tokenOwner, uint256 amount); constructor(address _KEEPER, address _aKEEPER, address _staking) { require( _KEEPER != address(0) ); require( _aKEEPER != address(0) ); require( _staking != address(0) ); KEEPER = IERC20(_KEEPER); aKEEPER = IERC20(_aKEEPER); staking = _staking; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } function migrate(uint256 amount) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); KEEPER.transfer(msg.sender, amount); emit KeeperRedeemed(msg.sender, amount); } function migrateTrove(uint256 amount, bool _wrap) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); IERC20( KEEPER ).approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); emit TroveRedeemed(msg.sender, amount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/AggregateV3Interface.sol"; contract aKeeperPresale is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public aKEEPER; address public USDC; address public USDT; address public DAI; address public wBTC; address public gnosisSafe; mapping( address => uint ) public amountInfo; uint deadline; AggregatorV3Interface internal ethPriceFeed; AggregatorV3Interface internal btcPriceFeed; event aKeeperRedeemed(address tokenOwner, uint amount); constructor(address _aKEEPER, address _USDC, address _USDT, address _DAI, address _wBTC, address _ethFeed, address _btcFeed, address _gnosisSafe, uint _deadline) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); require( _USDT != address(0) ); require( _DAI != address(0) ); require( _wBTC != address(0) ); require( _ethFeed != address(0) ); require( _btcFeed != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = _USDC; USDT = _USDT; DAI = _DAI; wBTC = _wBTC; gnosisSafe = _gnosisSafe; deadline = _deadline; ethPriceFeed = AggregatorV3Interface( _ethFeed ); btcPriceFeed = AggregatorV3Interface( _btcFeed ); } function setDeadline(uint _deadline) external onlyOwner() { deadline = _deadline; } function ethAssetPrice() public view returns (int) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return price; } function btcAssetPrice() public view returns (int) { ( , int price, , , ) = btcPriceFeed.latestRoundData(); return price; } function maxAmount() internal pure returns (uint) { return 100000000000; } function getTokens(address principle, uint amount) external { require(block.timestamp < deadline, "Deadline has passed."); require(principle == USDC || principle == USDT || principle == DAI || principle == wBTC, "Token is not acceptable."); require(IERC20(principle).balanceOf(msg.sender) >= amount, "Not enough token amount."); // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount; if (principle == DAI) { aKeeperAmount = amount.div(1e11); } else if (principle == wBTC) { aKeeperAmount = amount.mul(uint(btcAssetPrice())).div(1e9); } else { aKeeperAmount = amount.mul(1e1); } require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); IERC20(principle).safeTransferFrom(msg.sender, gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function getTokensEth() external payable { require(block.timestamp < deadline, "Deadline has passed."); uint amount = msg.value; // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount = amount.mul(uint(ethAssetPrice())).div(1e19); require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); safeTransferETH(gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); require( msg.value == 0 || _amount == msg.value, "Amount should be equal to ETH transferred"); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract aKeeperAirdrop is Ownable { using SafeMath for uint; IERC20 public aKEEPER; IERC20 public USDC; address public gnosisSafe; constructor(address _aKEEPER, address _USDC, address _gnosisSafe) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = IERC20(_USDC); gnosisSafe = _gnosisSafe; } receive() external payable { } function airdropTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { aKEEPER.transfer(_recipients[i], _amounts[i]); } } function refundUsdcTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { USDC.transfer(_recipients[i], _amounts[i]); } } function refundEth(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { safeTransferETH(_recipients[i], _amounts[i]); } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawUsdc() external onlyOwner() { uint256 amount = USDC.balanceOf(address(this)); USDC.transfer(gnosisSafe, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ILPCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ISPV.sol"; import "./interfaces/IStaking.sol"; contract Treasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event Deposit( address indexed token, uint amount, uint value ); event DepositEth( uint amount, uint value ); event Sell( address indexed token, uint indexed amount, uint indexed price ); event SellEth( uint indexed amount, uint indexed price ); event ReservesWithdrawn( address indexed caller, address indexed token, uint amount ); event ReservesUpdated( uint indexed totalReserves ); event ReservesAudited( uint indexed totalReserves ); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); event SPVUpdated( address indexed spv ); enum MANAGING { RESERVETOKEN, LIQUIDITYTOKEN, VARIABLETOKEN } struct PriceFeed { address feed; uint decimals; } IKeplerERC20 immutable KEEPER; uint public constant keeperDecimals = 9; uint public immutable priceAdjust; // 4 decimals. 1000 = 0.1 address[] public reserveTokens; mapping( address => bool ) public isReserveToken; address[] public variableTokens; mapping( address => bool ) public isVariableToken; address[] public liquidityTokens; mapping( address => bool ) public isLiquidityToken; mapping( address => address ) public lpCalculator; // bond calculator for liquidity token mapping( address => PriceFeed ) public priceFeeds; // price feeds for variable token uint public totalReserves; uint public spvDebt; uint public daoDebt; uint public ownerDebt; uint public reserveLastAudited; AggregatorV3Interface internal ethPriceFeed; address public staking; address public vesting; address public SPV; address public immutable DAO; uint public daoRatio; // 4 decimals. 1000 = 0.1 uint public spvRatio; // 4 decimals. 7000 = 0.7 uint public vestingRatio; // 4 decimals. 1000 = 0.1 uint public stakeRatio; // 4 decimals. 9000 = 0.9 uint public lcv; // 4 decimals. 1000 = 0.1 uint public keeperSold; uint public initPrice; // To deposit initial reserves when price is undefined (Keeper supply = 0) constructor (address _KEEPER, address _USDC, address _USDT, address _DAI, address _DAO, address _vesting, address _ethPriceFeed, uint _priceAdjust, uint _initPrice) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); require( _DAO != address(0) ); DAO = _DAO; require( _vesting != address(0) ); vesting = _vesting; isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _USDT] = true; reserveTokens.push( _USDT ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); ethPriceFeed = AggregatorV3Interface( _ethPriceFeed ); priceAdjust = _priceAdjust; initPrice = _initPrice; } function treasuryInitialized() external onlyOwner() { initPrice = 0; } function setSPV(address _SPV) external onlyOwner() { require( _SPV != address(0), "Cannot be 0"); SPV = _SPV; emit SPVUpdated( SPV ); } function setVesting(address _vesting) external onlyOwner() { require( _vesting != address(0), "Cannot be 0"); vesting = _vesting; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0), "Cannot be 0"); staking = _staking; } function setLcv(uint _lcv) external onlyOwner() { require( lcv == 0 || _lcv <= lcv.mul(3).div(2), "LCV cannot change sharp" ); lcv = _lcv; } function setTreasuryRatio(uint _daoRatio, uint _spvRatio, uint _vestingRatio, uint _stakeRatio) external onlyOwner() { require( _daoRatio <= 1000, "DAO more than 10%" ); require( _spvRatio <= 7000, "SPV more than 70%" ); require( _vestingRatio <= 2000, "Vesting more than 20%" ); require( _stakeRatio >= 1000 && _stakeRatio <= 10000, "Stake ratio error" ); daoRatio = _daoRatio; spvRatio = _spvRatio; vestingRatio = _vestingRatio; stakeRatio = _stakeRatio; } function getPremium(uint _price) public view returns (uint) { return _price.mul( lcv ).mul( keeperSold ).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ).div( 1e4 ); } function getPrice() public view returns ( uint ) { if (initPrice != 0) { return initPrice; } else { return totalReserves.add(ownerDebt).add( ISPV(SPV).totalValue() ).add( priceAdjust ).mul(10 ** keeperDecimals).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ); } } function ethAssetPrice() public view returns (uint) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 1e8 ); } function variableAssetPrice(address _address, uint _decimals) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface(_address).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** _decimals ); } function EthToUSD( uint _amount ) internal view returns ( uint ) { return _amount.mul( ethAssetPrice() ).div( 1e18 ); } function auditTotalReserves() public { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < variableTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( variableTokens[ i ], IERC20Extended( variableTokens[ i ] ).balanceOf( address(this) ) ) ); } reserves = reserves.add( EthToUSD(address(this).balance) ); totalReserves = reserves; reserveLastAudited = block.timestamp; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice allow depositing an asset for KEEPER @param _amount uint @param _token address @return send_ uint */ function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // IERC20Extended( _token ).safeTransfer( DAO, daoAmount ); uint value = valueOfToken(_token, _amount); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } function depositEth( uint _amount, bool _stake ) external payable returns ( uint send_ ) { require( _amount == msg.value, "Amount should be equal to ETH transferred"); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // safeTransferETH(DAO, daoAmount); uint value = EthToUSD( _amount ); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit DepositEth( _amount, value ); } function sendOrStake(address _recipient, uint _value, bool _stake) internal returns (uint send_) { send_ = _value.mul( 10 ** keeperDecimals ).div( getPrice() ); if ( _stake ) { KEEPER.mint( address(this), send_ ); KEEPER.approve( staking, send_ ); IStaking( staking ).stake( send_, _recipient, false ); } else { KEEPER.mint( _recipient, send_ ); } uint vestingAmount = send_.mul(vestingRatio).div(1e4); KEEPER.mint( vesting, vestingAmount ); } /** @notice allow to burn KEEPER for reserves @param _amount uint of keeper @param _token address */ function sell( uint _amount, address _token ) external { require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul( 10 ** IERC20Extended( _token ).decimals() ).div( 10 ** keeperDecimals ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); IERC20Extended(_token).safeTransfer(msg.sender, sellAmount); IERC20Extended(_token).safeTransfer(DAO, daoAmount); emit Sell( _token, _amount, sellPrice ); } function sellEth( uint _amount ) external { (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul(10 ** 18).div( ethAssetPrice() ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); safeTransferETH(msg.sender, sellAmount); safeTransferETH(DAO, daoAmount); emit SellEth( _amount, sellPrice ); } function sellKeeperBurn(address _sender, uint _amount) internal returns (uint price, uint premium, uint sellPrice) { price = getPrice(); premium = getPremium(price); sellPrice = price.sub(premium); KEEPER.burnFrom( _sender, _amount ); keeperSold = keeperSold.add( _amount ); uint stakeRewards = _amount.mul(stakeRatio).mul(premium).div(price).div(1e4); KEEPER.mint( address(this), stakeRewards ); KEEPER.approve( staking, stakeRewards ); IStaking( staking ).addRebaseReward( stakeRewards ); } function unstakeMint(uint _amount) external { require( msg.sender == staking, "Not allowed." ); KEEPER.mint(msg.sender, _amount); } function initDeposit( address _token, uint _amount ) external payable onlyOwner() { require( initPrice != 0, "Already initialized" ); uint value; if ( _token == address(0) && msg.value != 0 ) { require( _amount == msg.value, "Amount mismatch" ); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); uint send_ = value.mul( 10 ** keeperDecimals ).div( getPrice() ); KEEPER.mint( msg.sender, send_ ); } /** @notice allow owner multisig to withdraw assets on debt (for safe investments) @param _token address @param _amount uint */ function incurDebt( address _token, uint _amount, bool isEth ) external onlyOwner() { uint value; if ( _token == address(0) && isEth ) { safeTransferETH(msg.sender, _amount); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.sub( value ); ownerDebt = ownerDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( msg.sender, _token, _amount ); } function repayDebt( address _token, uint _amount, bool isEth ) external payable onlyOwner() { uint value; if ( isEth ) { require( msg.value == _amount, "Amount mismatch" ); value = EthToUSD( _amount ); } else { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); if ( value > ownerDebt ) { uint daoProfit = _amount.mul( daoRatio ).mul( value.sub(ownerDebt) ).div( value ).div(1e4); if ( isEth ) { safeTransferETH( DAO, daoProfit ); } else { IERC20Extended( _token ).safeTransfer( DAO, daoProfit ); } value = ownerDebt; } ownerDebt = ownerDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVDeposit( address _token, uint _amount ) external { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken(_token, _amount); totalReserves = totalReserves.add( value ); if ( value > spvDebt ) { value = spvDebt; } spvDebt = spvDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVWithdraw( address _token, uint _amount ) external { require( msg.sender == SPV, "Only SPV" ); address SPVWallet = ISPV( SPV ).SPVWallet(); uint value = valueOfToken(_token, _amount); uint totalValue = totalReserves.add( ISPV(SPV).totalValue() ).add( ownerDebt ); require( spvDebt.add(value) < totalValue.mul(spvRatio).div(1e4), "Debt exceeded" ); spvDebt = spvDebt.add(value); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( SPVWallet, _amount ); } function DAOWithdraw( address _token, uint _amount, bool isEth ) external { require( msg.sender == DAO, "Only DAO Allowed" ); uint value; if ( _token == address(0) && isEth ) { value = EthToUSD( _amount ); } else { value = valueOfToken(_token, _amount); } uint daoProfit = ISPV( SPV ).totalProfit().mul( daoRatio ).div(1e4); require( daoDebt.add(value) <= daoProfit, "Too much" ); if ( _token == address(0) && isEth ) { safeTransferETH(DAO, _amount); } else { IERC20Extended( _token ).safeTransfer( DAO, _amount ); } totalReserves = totalReserves.sub( value ); daoDebt = daoDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( DAO, _token, _amount ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() ); } else if ( isLiquidityToken[ _token ] ) { value_ = ILPCalculator( lpCalculator[ _token ] ).valuationUSD( _token, _amount ); } else if ( isVariableToken[ _token ] ) { value_ = _amount.mul(variableAssetPrice( priceFeeds[_token].feed, priceFeeds[_token].decimals )).div( 10 ** IERC20Extended( _token ).decimals() ); } } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculatorFeed address @return bool */ function toggle( MANAGING _managing, address _address, address _calculatorFeed, uint decimals ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); bool result; if ( _managing == MANAGING.RESERVETOKEN ) { // 0 if( !listContains( reserveTokens, _address ) ) { reserveTokens.push( _address ); } result = !isReserveToken[ _address ]; isReserveToken[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 1 if( !listContains( liquidityTokens, _address ) ) { liquidityTokens.push( _address ); } result = !isLiquidityToken[ _address ]; isLiquidityToken[ _address ] = result; lpCalculator[ _address ] = _calculatorFeed; } else if ( _managing == MANAGING.VARIABLETOKEN ) { // 2 if( !listContains( variableTokens, _address ) ) { variableTokens.push( _address ); } result = !isVariableToken[ _address ]; isVariableToken[ _address ] = result; priceFeeds[ _address ] = PriceFeed({ feed: _calculatorFeed, decimals: decimals }); } else return false; emit ChangeActivated( _managing, _address, result ); return true; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains( address[] storage _list, address _token ) internal view returns ( bool ) { for( uint i = 0; i < _list.length; i++ ) { if( _list[ i ] == _token ) { return true; } } return false; } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ILPCalculator { function valuationUSD( address _token, uint _amount ) external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(address account_, uint256 ammount_) external; function burn(uint256 amount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ISPV { function SPVWallet() external view returns ( address ); function totalValue() external view returns ( uint ); function totalProfit() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake(uint _amount, address _recipient, bool _wrap) external; function addRebaseReward( uint _amount ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract aKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; uint public multiplier; // multiplier is 4 decimals i.e. 1000 = 0.1 event KeeperRedeemed(address tokenOwner, uint256 amount); constructor(address _aKEEPER, address _KEEPER, address _staking, uint _multiplier) { require( _aKEEPER != address(0) ); require( _KEEPER != address(0) ); require( _multiplier != 0 ); aKEEPER = IERC20(_aKEEPER); KEEPER = IERC20(_KEEPER); staking = _staking; multiplier = _multiplier; // reduce gas fees of migrate-stake by pre-approving large amount KEEPER.approve( staking, 1e25); } function migrate(uint256 amount, bool _stake, bool _wrap) public { aKEEPER.transferFrom(msg.sender, address(this), amount); uint keeperAmount = amount.mul(multiplier).div(1e4); if ( _stake && staking != address( 0 ) ) { IStaking( staking ).stake( keeperAmount, msg.sender, _wrap ); } else { KEEPER.transfer(msg.sender, keeperAmount); } emit KeeperRedeemed(msg.sender, keeperAmount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract SPV is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event TokenAdded( address indexed token, PRICETYPE indexed priceType, uint indexed price ); event TokenPriceUpdate( address indexed token, uint indexed price ); event TokenPriceTypeUpdate( address indexed token, PRICETYPE indexed priceType ); event TokenRemoved( address indexed token ); event ValueAudited( uint indexed total ); event TreasuryWithdrawn( address indexed token, uint indexed amount ); event TreasuryReturned( address indexed token, uint indexed amount ); uint public constant keeperDecimals = 9; enum PRICETYPE { STABLE, CHAINLINK, UNISWAP, MANUAL } struct TokenPrice { address token; PRICETYPE priceType; uint price; // At keeper decimals } TokenPrice[] public tokens; struct ChainlinkPriceFeed { address feed; uint decimals; } mapping( address => ChainlinkPriceFeed ) public chainlinkPriceFeeds; mapping( address => address ) public uniswapPools; // The other token must be a stablecoin address public immutable treasury; address public SPVWallet; uint public totalValue; uint public totalProfit; uint public spvRecordedValue; uint public recordTime; uint public profitInterval; bool public allowUpdate; // False when SPV is transferring funds constructor (address _treasury, address _USDC, address _USDT, address _DAI, address _SPVWallet, uint _profitInterval) { require( _treasury != address(0) ); treasury = _treasury; require( _SPVWallet != address(0) ); SPVWallet = _SPVWallet; tokens.push(TokenPrice({ token: _USDC, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _USDT, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _DAI, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); recordTime = block.timestamp; require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; spvRecordedValue = 0; allowUpdate = true; updateTotalValue(); } function enableUpdates() external onlyOwner() { allowUpdate = true; } function disableUpdates() external onlyOwner() { allowUpdate = false; } function setInterval( uint _profitInterval ) external onlyOwner() { require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; } function chainlinkTokenPrice(address _token) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface( chainlinkPriceFeeds[_token].feed ).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** chainlinkPriceFeeds[_token].decimals ); } function uniswapTokenPrice(address _token) public view returns (uint) { address _pair = uniswapPools[_token]; ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; address reserveToken; uint tokenAmount; if ( IUniswapV2Pair( _pair ).token0() == _token ) { reserveToken = IUniswapV2Pair( _pair ).token1(); reserve = reserve1; tokenAmount = reserve0; } else { reserveToken = IUniswapV2Pair( _pair ).token0(); reserve = reserve0; tokenAmount = reserve1; } return reserve.mul(10 ** keeperDecimals).mul( 10 ** IERC20Extended(_token).decimals() ).div( tokenAmount ).div( 10 ** IERC20Extended(reserveToken).decimals() ); } function setNewTokenPrice(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) internal returns (uint tokenPrice) { if (_priceType == PRICETYPE.STABLE) { tokenPrice = 10 ** keeperDecimals; } else if (_priceType == PRICETYPE.CHAINLINK) { chainlinkPriceFeeds[_token] = ChainlinkPriceFeed({ feed: _feedOrPool, decimals: _decimals }); tokenPrice = chainlinkTokenPrice(_token); } else if (_priceType == PRICETYPE.UNISWAP) { uniswapPools[_token] = _feedOrPool; tokenPrice = uniswapTokenPrice(_token); } else if (_priceType == PRICETYPE.MANUAL) { tokenPrice = _price; } else { tokenPrice = 0; } } function addToken(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) external onlyOwner() { uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens.push(TokenPrice({ token: _token, priceType: _priceType, price: tokenPrice })); updateTotalValue(); emit TokenAdded(_token, _priceType, tokenPrice); } function updateTokenPrice( uint _index, address _token, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); require( tokens[ _index ].priceType == PRICETYPE.MANUAL, "Only manual tokens can be updated" ); tokens[ _index ].price = _price; updateTotalValue(); emit TokenPriceUpdate(_token, _price); } function updateTokenPriceType( uint _index, address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ].priceType = _priceType; uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens[ _index ].price = tokenPrice; updateTotalValue(); emit TokenPriceTypeUpdate(_token, _priceType); emit TokenPriceUpdate(_token, tokenPrice); } function removeToken( uint _index, address _token ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ] = tokens[tokens.length-1]; tokens.pop(); updateTotalValue(); emit TokenRemoved(_token); } function getTokenBalance( uint _index ) internal view returns (uint) { address _token = tokens[ _index ].token; return IERC20Extended(_token).balanceOf( SPVWallet ).mul(tokens[ _index ].price).div( 10 ** IERC20Extended( _token ).decimals() ); } function auditTotalValue() external { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { PRICETYPE priceType = tokens[i].priceType; if (priceType == PRICETYPE.CHAINLINK) { tokens[i].price = chainlinkTokenPrice(tokens[i].token); } else if (priceType == PRICETYPE.UNISWAP) { tokens[i].price = uniswapTokenPrice(tokens[i].token); } newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; emit ValueAudited(totalValue); } } function calculateProfits() external { require( recordTime.add( profitInterval ) <= block.timestamp, "Not yet" ); require( msg.sender == SPVWallet || msg.sender == ITreasury( treasury ).DAO(), "Not allowed" ); recordTime = block.timestamp; updateTotalValue(); uint currentValue; uint treasuryDebt = ITreasury( treasury ).spvDebt(); if ( treasuryDebt > totalValue ) { currentValue = 0; } else { currentValue = totalValue.sub(treasuryDebt); } if ( currentValue > spvRecordedValue ) { uint profit = currentValue.sub( spvRecordedValue ); spvRecordedValue = currentValue; totalProfit = totalProfit.add(profit); } } function treasuryWithdraw( uint _index, address _token, uint _amount ) external { require( msg.sender == SPVWallet, "Only SPV Wallet allowed" ); require( _token == tokens[ _index ].token, "Wrong token" ); ITreasury( treasury ).SPVWithdraw( _token, _amount ); updateTotalValue(); emit TreasuryWithdrawn( _token, _amount ); } function returnToTreasury( uint _index, address _token, uint _amount ) external { require( _token == tokens[ _index ].token, "Wrong token" ); require( msg.sender == SPVWallet, "Only SPV Wallet can return." ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20Extended( _token ).approve( treasury, _amount ); ITreasury( treasury ).SPVDeposit( _token, _amount ); updateTotalValue(); emit TreasuryReturned( _token, _amount ); } function migrateTokens( address newSPV ) external onlyOwner() { for ( uint i = 0; i < tokens.length; i++ ) { address _token = tokens[ i ].token; IERC20Extended(_token).transfer(newSPV, IERC20Extended(_token).balanceOf( address(this) ) ); } safeTransferETH(newSPV, address(this).balance ); } function updateTotalValue() internal { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function unstakeMint( uint _amount ) external; function SPVDeposit( address _token, uint _amount ) external; function SPVWithdraw( address _token, uint _amount ) external; function DAO() external view returns ( address ); function spvDebt() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract LPCalculator { using SafeMath for uint; address public immutable KEEPER; uint public constant keeperDecimals = 9; constructor ( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function getReserve( address _pair ) public view returns ( address reserveToken, uint reserve ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; reserveToken = IUniswapV2Pair( _pair ).token1(); } else { reserve = reserve0; reserveToken = IUniswapV2Pair( _pair ).token0(); } } function valuationUSD( address _pair, uint _amount ) external view returns ( uint ) { uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); ( address reserveToken, uint reserve ) = getReserve( _pair ); return _amount.mul( reserve ).mul(2).mul( 10 ** keeperDecimals ).div( totalSupply ).div( 10 ** IERC20Extended( reserveToken ).decimals() ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; contract Staking is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; event Stake( address indexed recipient, uint indexed amount, uint indexed timestamp ); event Unstake( address indexed recipient, uint indexed amount, uint indexed timestamp ); uint public constant keeperDecimals = 9; IERC20 public immutable KEEPER; address public immutable treasury; uint public rate; // 6 decimals. 10000 = 0.01 = 1% uint public INDEX; // keeperDecimals decimals uint public keeperRewards; struct Rebase { uint rebaseRate; // 6 decimals uint totalStaked; uint index; uint timeOccured; } struct Epoch { uint number; uint rebaseInterval; uint nextRebase; } Epoch public epoch; Rebase[] public rebases; // past rebase data mapping(address => uint) public stakers; constructor( address _KEEPER, address _treasury, uint _rate, uint _INDEX, uint _rebaseInterval ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); require( _treasury != address(0) ); treasury = _treasury; require( _rate != 0 ); rate = _rate; require( _INDEX != 0 ); INDEX = _INDEX; require( _rebaseInterval != 0 ); epoch = Epoch({ number: 1, rebaseInterval: _rebaseInterval, nextRebase: block.timestamp.add(_rebaseInterval) }); } function setRate( uint _rate ) external onlyOwner() { require( _rate >= rate.div(2) && _rate <= rate.mul(3).div(2), "Rate change cannot be too sharp." ); rate = _rate; } function stake( uint _amount, address _recipient, bool _wrap ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); uint _gonsAmount = getGonsAmount( _amount ); stakers[ _recipient ] = stakers[ _recipient ].add( _gonsAmount ); emit Stake( _recipient, _amount, block.timestamp ); rebase(); } function unstake( uint _amount ) external { rebase(); require( _amount <= stakerAmount(msg.sender), "Cannot unstake more than possible." ); if ( _amount > KEEPER.balanceOf( address(this) ) ) { ITreasury(treasury).unstakeMint( _amount.sub(KEEPER.balanceOf( address(this) ) ) ); } uint gonsAmount = getGonsAmount( _amount ); // Handle math precision error if ( gonsAmount > stakers[msg.sender] ) { gonsAmount = stakers[msg.sender]; } stakers[msg.sender] = stakers[ msg.sender ].sub(gonsAmount); KEEPER.safeTransfer( msg.sender, _amount ); emit Unstake( msg.sender, _amount, block.timestamp ); } function rebase() public { if (epoch.nextRebase <= block.timestamp) { uint rebasingRate = rebaseRate(); INDEX = INDEX.add( INDEX.mul( rebasingRate ).div(1e6) ); epoch.nextRebase = epoch.nextRebase.add(epoch.rebaseInterval); epoch.number++; keeperRewards = 0; rebases.push( Rebase({ rebaseRate: rebasingRate, totalStaked: KEEPER.balanceOf( address(this) ), index: INDEX, timeOccured: block.timestamp }) ); } } function stakerAmount( address _recipient ) public view returns (uint) { return getKeeperAmount(stakers[ _recipient ]); } function rebaseRate() public view returns (uint) { uint keeperBalance = KEEPER.balanceOf( address(this) ); if (keeperBalance == 0) { return rate; } else { return rate.add( keeperRewards.mul(1e6).div( KEEPER.balanceOf( address(this) ) ) ); } } function addRebaseReward( uint _amount ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); keeperRewards = keeperRewards.add( _amount ); } function getGonsAmount( uint _amount ) internal view returns (uint) { return _amount.mul(10 ** keeperDecimals).div(INDEX); } function getKeeperAmount( uint _gons ) internal view returns (uint) { return _gons.mul(INDEX).div(10 ** keeperDecimals); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract MockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract KeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract KeeperVesting is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public immutable KEEPER; event KeeperRedeemed(address redeemer, uint amount); struct Term { uint percent; // 6 decimals % ( 5000 = 0.5% = 0.005 ) uint claimed; } mapping(address => Term) public terms; mapping(address => address) public walletChange; // uint public totalRedeemable; // uint public redeemableLastUpdated; uint public totalRedeemed; // address public redeemUpdater; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); // redeemUpdater = _redeemUpdater; // redeemableLastUpdated = block.timestamp; } // function setRedeemUpdater(address _redeemUpdater) external onlyOwner() { // require( _redeemUpdater != address(0) ); // redeemUpdater = _redeemUpdater; // } // Sets terms for a new wallet function setTerms(address _vester, uint _percent ) external onlyOwner() returns ( bool ) { terms[_vester].percent = _percent; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _percents ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].percent = _percents[i]; } return true; } // function updateTotalRedeemable() external { // require( msg.sender == redeemUpdater, "Only redeem updater can call." ); // uint keeperBalance = KEEPER.balanceOf( address(this) ); // uint newRedeemable = keeperBalance.add(totalRedeemed).mul(block.timestamp.sub(redeemableLastUpdated)).div(31536000); // totalRedeemable = totalRedeemable.add(newRedeemable); // if (totalRedeemable > keeperBalance ) { // totalRedeemable = keeperBalance; // } // redeemableLastUpdated = block.timestamp; // } // Allows wallet to redeem KEEPER function redeem( uint _amount ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); KEEPER.safeTransfer(msg.sender, _amount); terms[ msg.sender ].claimed = info.claimed.add( _amount ); totalRedeemed = totalRedeemed.add(_amount); emit KeeperRedeemed(msg.sender, _amount); return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].percent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { uint maxRedeemable = KEEPER.balanceOf( address(this) ).add( totalRedeemed ); if ( maxRedeemable > 1e17 ) { maxRedeemable = 1e17; } uint maxRedeemableUser = maxRedeemable.mul( _info.percent ).div(1e6); return maxRedeemableUser.sub(_info.claimed); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; interface KeeperCompatibleInterface { function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); function performUpkeep(bytes calldata performData) external; } interface IStaking { function rebase() external; } interface ITreasury { function auditTotalReserves() external; } interface ISPV { function auditTotalValue() external; } contract DailyUpkeep is KeeperCompatibleInterface, Ownable { /** * Use an interval in seconds and a timestamp to slow execution of Upkeep */ uint public immutable interval; uint public nextTimeStamp; address public staking; address public treasury; address public spv; constructor(address _staking, address _treasury, address _spv, uint _nextTimeStamp, uint _interval) { staking = _staking; treasury = _treasury; spv = _spv; nextTimeStamp = _nextTimeStamp; interval = _interval; } function setStaking(address _staking) external onlyOwner() { staking = _staking; } function setTreasury(address _treasury) external onlyOwner() { treasury = _treasury; } function setSPV(address _spv) external onlyOwner() { spv = _spv; } function checkUpkeep(bytes calldata /* checkData */) external override returns (bool upkeepNeeded, bytes memory /* performData */) { upkeepNeeded = block.timestamp > nextTimeStamp; } function performUpkeep(bytes calldata /* performData */) external override { if (staking != address(0)) { IStaking(staking).rebase(); } if (treasury != address(0)) { ITreasury(treasury).auditTotalReserves(); } if (spv != address(0)) { ISPV(spv).auditTotalValue(); } nextTimeStamp = nextTimeStamp + interval; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldMockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract iKeeperIndexCalculator is Ownable { using SafeMath for uint; event AssetIndexAdded( uint indexed deposit, uint indexed price, address indexed token ); event IndexUpdated( uint indexed fromIndex, uint indexed toIndex, uint oldPrice, uint newPrice ); event DepositUpdated( uint indexed fromDeposit, uint indexed toDeposit ); event AssetIndexWithdrawn( uint indexed deposit, uint price, uint indexed index, address indexed token ); struct AssetIndex { uint deposit; // In USD uint price; // 6 decimals, in USD uint index; // 9 decimals, starts with 1000000000 address token; // Token address of the asset } AssetIndex[] public indices; uint public netIndex; constructor(uint _netIndex) { require( _netIndex != 0, "Index cannot be 0" ); netIndex = _netIndex; } function calculateIndex() public { uint indexProduct = 0; uint totalDeposit = 0; for (uint i=0; i < indices.length; i++) { uint deposit = indices[i].deposit; totalDeposit = totalDeposit.add(deposit); indexProduct = indexProduct.add( indices[i].index.mul( deposit ) ); } netIndex = indexProduct.div(totalDeposit); } function addAssetIndex(uint _deposit, uint _price, address _token) external onlyOwner() { indices.push( AssetIndex({ deposit: _deposit, price: _price, index: 1e9, token: _token })); } function updateIndex(uint _index, address _token, uint _newPrice) external onlyOwner() { AssetIndex storage assetIndex = indices[ _index ]; require(assetIndex.token == _token, "Wrong index."); uint changeIndex = _newPrice.mul(1e9).div(assetIndex.price); uint fromIndex = assetIndex.index; uint oldPrice = assetIndex.price; assetIndex.index = fromIndex.mul(changeIndex).div(1e9); assetIndex.deposit = assetIndex.deposit.mul(changeIndex).div(1e9); assetIndex.price = _newPrice; emit IndexUpdated(fromIndex, assetIndex.index, oldPrice, _newPrice); } function updateDeposit(uint _index, address _token, uint _amount, bool _add) external onlyOwner() { require(_token == indices[ _index ].token, "Wrong index."); uint oldDeposit = indices[ _index ].deposit; require(_add || oldDeposit >= _amount, "Cannot withdraw more than deposit"); if (!_add) { indices[ _index ].deposit = oldDeposit.sub(_amount); } else { indices[ _index ].deposit = oldDeposit.add(_amount); } emit DepositUpdated(oldDeposit, indices[ _index ].deposit); } function withdrawAsset(uint _index, address _token) external onlyOwner() { AssetIndex memory assetIndex = indices[ _index ]; require(_token == assetIndex.token, "Wrong index."); indices[ _index ] = indices[indices.length-1]; indices.pop(); emit AssetIndexWithdrawn(assetIndex.deposit, assetIndex.price, assetIndex.index, assetIndex.token); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IStaking.sol"; // import "./interfaces/IIndexCalculator.sol"; contract iKEEPER is ERC20, Ownable { using SafeMath for uint; address public immutable TROVE; address public immutable staking; address public indexCalculator; constructor(address _TROVE, address _staking, address _indexCalculator) ERC20("Invest KEEPER", "iKEEPER") { require(_TROVE != address(0)); TROVE = _TROVE; require(_staking != address(0)); staking = _staking; require(_indexCalculator != address(0)); indexCalculator = _indexCalculator; } // function setIndexCalculator( address _indexCalculator ) external onlyOwner() { // require( _indexCalculator != address(0) ); // indexCalculator = _indexCalculator; // } // /** // @notice get iKEEPER index (9 decimals) // @return uint // */ // // function getIndex() public view returns (uint) { // // return IIndexCalculator(indexCalculator).netIndex(); // // } // // /** // // @notice wrap KEEPER // // @param _amount uint // // @return uint // // */ // // function wrapKEEPER( uint _amount ) external returns ( uint ) { // // IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); // // uint value = TROVEToiKEEPER( _amount ); // // _mint( msg.sender, value ); // // return value; // // } // /** // @notice wrap TROVE // @param _amount uint // @return uint // */ // function wrap( uint _amount, address _recipient ) external returns ( uint ) { // IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); // uint value = TROVEToiKEEPER( _amount ); // _mint( _recipient, value ); // return value; // } // // /** // // @notice unwrap KEEPER // // @param _amount uint // // @return uint // // */ // // function unwrapKEEPER( uint _amount ) external returns ( uint ) { // // _burn( msg.sender, _amount ); // // uint value = iKEEPERToTROVE( _amount ); // // uint keeperBalance = IERC20(KEEPER).balanceOf( address(this) ); // // if (keeperBalance < value ) { // // uint difference = value.sub(keeperBalance); // // require(IsKEEPER(TROVE).balanceOf(address(this)) >= difference, "Contract does not have enough TROVE"); // // IsKEEPER(TROVE).approve(staking, difference); // // IStaking(staking).unstake(difference, false); // // } // // IERC20( KEEPER ).transfer( msg.sender, value ); // // return value; // // } // /** // @notice unwrap TROVE // @param _amount uint // @return uint // */ // function unwrap( uint _amount ) external returns ( uint ) { // _burn( msg.sender, _amount ); // uint value = iKEEPERToTROVE( _amount ); // IsKEEPER( TROVE ).transfer( msg.sender, value ); // return value; // } // /** // @notice converts iKEEPER amount to TROVE // @param _amount uint // @return uint // */ // function iKEEPERToTROVE( uint _amount ) public view returns ( uint ) { // return _amount.mul( getIndex() ).div( 10 ** decimals() ); // } // /** // @notice converts TROVE amount to iKEEPER // @param _amount uint // @return uint // */ // function TROVEToiKEEPER( uint _amount ) public view returns ( uint ) { // return _amount.mul( 10 ** decimals() ).div( getIndex() ); // } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // intermediate token address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint gonsPayout; // sKEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _wrap bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./libraries/FixedPoint.sol"; interface IBondingCalculator { function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } contract StandardBondingCalculator is IBondingCalculator { using FixedPoint for *; using SafeMath for uint; using SafeMath for uint112; address public immutable KEEPER; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = a.div(2).add(1); while (b < c) { c = b; b = a.div(b).add(b).div(2); } } else if (a != 0) { c = 1; } } function getKValue( address _pair ) public view returns( uint k_ ) { uint token0 = IERC20Extended( IUniswapV2Pair( _pair ).token0() ).decimals(); uint token1 = IERC20Extended( IUniswapV2Pair( _pair ).token1() ).decimals(); (uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint totalDecimals = token0.add( token1 ); uint pairDecimal = IERC20Extended( _pair ).decimals(); if (totalDecimals < pairDecimal) { uint decimals = pairDecimal.sub(totalDecimals); k_ = reserve0.mul(reserve1).mul(10 ** decimals); } else { uint decimals = totalDecimals.sub(pairDecimal); k_ = reserve0.mul(reserve1).div(10 ** decimals); } } function getTotalValue( address _pair ) public view returns ( uint _value ) { _value = sqrrt(getKValue( _pair )).mul(2); } function valuation( address _pair, uint amount_ ) external view override returns ( uint _value ) { uint totalValue = getTotalValue( _pair ); uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); _value = totalValue.mul( FixedPoint.fraction( amount_, totalSupply ).decode112with18() ).div( 1e18 ); } function markdown( address _pair ) external view returns ( uint ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; } else { reserve = reserve0; } return reserve.mul( 2 * ( 10 ** IERC20Extended( KEEPER ).decimals() ) ).div( getTotalValue( _pair ) ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract aKEEPER is ERC20 { constructor() ERC20("Alpha Keeper", "aKEEPER") { _setupDecimals(9); _mint(msg.sender, 220000000000000); } function burn(uint256 amount) external { _burn(msg.sender, amount); } }
Maximum KEEPER supply for percent increase
uint private constant TOUCHDOWN = 5000000 * 10**9;
12,150,376
[ 1, 13528, 1475, 9383, 3194, 14467, 364, 5551, 10929, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 3238, 5381, 8493, 57, 1792, 12711, 273, 1381, 9449, 380, 1728, 636, 29, 31, 377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright 2019 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. // TO-DO: Add documentation explaining each instruction /// @title EnvTrapIntInstruction pragma solidity ^0.7.0; import "../MemoryInteractor.sol"; import "../RiscVDecoder.sol"; import "../RiscVConstants.sol"; import "../Exceptions.sol"; library EnvTrapIntInstructions { function executeECALL( MemoryInteractor mi ) public { uint64 priv = mi.readIflagsPrv(); uint64 mtval = mi.readMtval(); // TO-DO: Are parameter valuation order deterministic? If so, we dont need to allocate memory Exceptions.raiseException( mi, Exceptions.getMcauseEcallBase() + priv, mtval ); } function executeEBREAK( MemoryInteractor mi ) public { Exceptions.raiseException( mi, Exceptions.getMcauseBreakpoint(), mi.readMtval() ); } function executeSRET( MemoryInteractor mi ) public returns (bool) { uint64 priv = mi.readIflagsPrv(); uint64 mstatus = mi.readMstatus(); if (priv < RiscVConstants.getPrvS() || (priv == RiscVConstants.getPrvS() && (mstatus & RiscVConstants.getMstatusTsrMask() != 0))) { return false; } else { uint64 spp = (mstatus & RiscVConstants.getMstatusSppMask()) >> RiscVConstants.getMstatusSppShift(); // Set the IE state to previous IE state uint64 spie = (mstatus & RiscVConstants.getMstatusSpieMask()) >> RiscVConstants.getMstatusSpieShift(); mstatus = (mstatus & ~RiscVConstants.getMstatusSieMask()) | (spie << RiscVConstants.getMstatusSieShift()); // set SPIE to 1 mstatus |= RiscVConstants.getMstatusSpieMask(); // set SPP to U mstatus &= ~RiscVConstants.getMstatusSppMask(); mi.writeMstatus(mstatus); if (priv != spp) { mi.setPriv(spp); } mi.writePc(mi.readSepc()); return true; } } function executeMRET( MemoryInteractor mi ) public returns(bool) { uint64 priv = mi.readIflagsPrv(); if (priv < RiscVConstants.getPrvM()) { return false; } else { uint64 mstatus = mi.readMstatus(); uint64 mpp = (mstatus & RiscVConstants.getMstatusMppMask()) >> RiscVConstants.getMstatusMppShift(); // set IE state to previous IE state uint64 mpie = (mstatus & RiscVConstants.getMstatusMpieMask()) >> RiscVConstants.getMstatusMpieShift(); mstatus = (mstatus & ~RiscVConstants.getMstatusMieMask()) | (mpie << RiscVConstants.getMstatusMieShift()); // set MPIE to 1 mstatus |= RiscVConstants.getMstatusMpieMask(); // set MPP to U mstatus &= ~RiscVConstants.getMstatusMppMask(); mi.writeMstatus(mstatus); if (priv != mpp) { mi.setPriv(mpp); } mi.writePc(mi.readMepc()); return true; } } function executeWFI( MemoryInteractor mi ) public returns(bool) { uint64 priv = mi.readIflagsPrv(); uint64 mstatus = mi.readMstatus(); if (priv == RiscVConstants.getPrvU() || (priv == RiscVConstants.getPrvS() && (mstatus & RiscVConstants.getMstatusTwMask() != 0))) { return false; } else { uint64 mip = mi.readMip(); uint64 mie = mi.readMie(); // Go to power down if no enable interrupts are pending if ((mip & mie) == 0) { mi.setIflagsI(true); } return true; } } }
Set the IE state to previous IE state set SPIE to 1 set SPP to U
function executeSRET( MemoryInteractor mi ) public returns (bool) { uint64 priv = mi.readIflagsPrv(); uint64 mstatus = mi.readMstatus(); if (priv < RiscVConstants.getPrvS() || (priv == RiscVConstants.getPrvS() && (mstatus & RiscVConstants.getMstatusTsrMask() != 0))) { return false; uint64 spp = (mstatus & RiscVConstants.getMstatusSppMask()) >> RiscVConstants.getMstatusSppShift(); uint64 spie = (mstatus & RiscVConstants.getMstatusSpieMask()) >> RiscVConstants.getMstatusSpieShift(); mstatus = (mstatus & ~RiscVConstants.getMstatusSieMask()) | (spie << RiscVConstants.getMstatusSieShift()); mstatus |= RiscVConstants.getMstatusSpieMask(); mstatus &= ~RiscVConstants.getMstatusSppMask(); mi.writeMstatus(mstatus); if (priv != spp) { mi.setPriv(spp); } mi.writePc(mi.readSepc()); return true; } }
7,212,434
[ 1, 694, 326, 10897, 919, 358, 2416, 10897, 919, 444, 20955, 41, 358, 404, 444, 348, 6584, 358, 587, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1836, 55, 10238, 12, 203, 3639, 9251, 2465, 3362, 12837, 203, 565, 262, 203, 565, 1071, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2254, 1105, 6015, 273, 12837, 18, 896, 2047, 80, 1341, 2050, 90, 5621, 203, 3639, 2254, 1105, 312, 2327, 273, 12837, 18, 896, 49, 2327, 5621, 203, 203, 3639, 309, 261, 11365, 411, 534, 291, 71, 58, 2918, 18, 588, 2050, 90, 55, 1435, 747, 261, 11365, 422, 534, 291, 71, 58, 2918, 18, 588, 2050, 90, 55, 1435, 597, 261, 81, 2327, 473, 534, 291, 71, 58, 2918, 18, 588, 49, 2327, 56, 11254, 5796, 1435, 480, 374, 20349, 288, 203, 5411, 327, 629, 31, 203, 5411, 2254, 1105, 1694, 84, 273, 261, 81, 2327, 473, 534, 291, 71, 58, 2918, 18, 588, 49, 2327, 3389, 84, 5796, 10756, 1671, 534, 291, 71, 58, 2918, 18, 588, 49, 2327, 3389, 84, 10544, 5621, 203, 5411, 2254, 1105, 1694, 1385, 273, 261, 81, 2327, 473, 534, 291, 71, 58, 2918, 18, 588, 49, 2327, 3389, 1385, 5796, 10756, 1671, 534, 291, 71, 58, 2918, 18, 588, 49, 2327, 3389, 1385, 10544, 5621, 203, 5411, 312, 2327, 273, 261, 81, 2327, 473, 4871, 54, 291, 71, 58, 2918, 18, 588, 49, 2327, 55, 1385, 5796, 10756, 571, 261, 1752, 1385, 2296, 534, 291, 71, 58, 2918, 18, 588, 49, 2327, 55, 1385, 10544, 10663, 203, 203, 5411, 312, 2327, 5626, 534, 291, 71, 58, 2918, 18, 588, 49, 2327, 3389, 1385, 5796, 5621, 203, 5411, 312, 2327, 12058, 2 ]
./full_match/1/0x9bfBD7CaDbF2AD0980eb04D6769E766c22E801CA/sources/src/ProtectionPlan.sol
* @notice Add beneficiaries for ERC1155 tokens @dev address(0) as a beneficiary is equivalent to removal @param _contract the ERC1155 contract @param _tokenIds the tokens of the ERC1155 contract @param _beneficiaries the beneficiaries for the tokens @param _amounts the amount of tokens for a beneficiary to inherit/
function _setInheritableERC1155( address _contract, uint256[] calldata _tokenIds, address[] calldata _beneficiaries, uint256[] calldata _amounts ) internal { if (_tokenIds.length != _beneficiaries.length || _tokenIds.length != _amounts.length) { revert BeneficiaryWalletsLengthMismatch(); } for (uint256 i = 0; i < _tokenIds.length;) { if (!IERC1155(_contract).isApprovedForAll(member, address(this))) { revert WillNotApproved(); } if (IERC1155(_contract).balanceOf(member, _tokenIds[i]) == 0) { revert InvalidAssetOwner(); } if (!beneficiaries[_beneficiaries[i]]) revert InvalidBeneficiary(); erc1155Registry[_contract][_tokenIds[i]][_beneficiaries[i]] = _amounts[i]; emit InheritableERC1155Set(member, _contract, _beneficiaries[i], _tokenIds[i], _amounts[i]); unchecked { i++; } } }
16,468,970
[ 1, 986, 27641, 74, 14463, 5646, 364, 4232, 39, 2499, 2539, 2430, 225, 1758, 12, 20, 13, 487, 279, 27641, 74, 14463, 814, 353, 7680, 358, 14817, 225, 389, 16351, 326, 4232, 39, 2499, 2539, 6835, 225, 389, 2316, 2673, 326, 2430, 434, 326, 4232, 39, 2499, 2539, 6835, 225, 389, 70, 4009, 74, 14463, 5646, 326, 27641, 74, 14463, 5646, 364, 326, 2430, 225, 389, 8949, 87, 326, 3844, 434, 2430, 364, 279, 27641, 74, 14463, 814, 358, 6811, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 14216, 429, 654, 39, 2499, 2539, 12, 203, 3639, 1758, 389, 16351, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 389, 2316, 2673, 16, 203, 3639, 1758, 8526, 745, 892, 389, 70, 4009, 74, 14463, 5646, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 389, 8949, 87, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 67, 2316, 2673, 18, 2469, 480, 389, 70, 4009, 74, 14463, 5646, 18, 2469, 747, 389, 2316, 2673, 18, 2469, 480, 389, 8949, 87, 18, 2469, 13, 288, 203, 5411, 15226, 605, 4009, 74, 14463, 814, 26558, 2413, 1782, 16901, 5621, 203, 3639, 289, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 2316, 2673, 18, 2469, 30943, 288, 203, 5411, 309, 16051, 45, 654, 39, 2499, 2539, 24899, 16351, 2934, 291, 31639, 1290, 1595, 12, 5990, 16, 1758, 12, 2211, 20349, 288, 203, 7734, 15226, 9980, 1248, 31639, 5621, 203, 5411, 289, 203, 5411, 309, 261, 45, 654, 39, 2499, 2539, 24899, 16351, 2934, 12296, 951, 12, 5990, 16, 389, 2316, 2673, 63, 77, 5717, 422, 374, 13, 288, 203, 7734, 15226, 1962, 6672, 5541, 5621, 203, 5411, 289, 203, 5411, 309, 16051, 70, 4009, 74, 14463, 5646, 63, 67, 70, 4009, 74, 14463, 5646, 63, 77, 65, 5717, 15226, 1962, 38, 4009, 74, 14463, 814, 5621, 203, 5411, 6445, 71, 2499, 2539, 4243, 63, 67, 16351, 6362, 67, 2316, 2673, 63, 77, 65, 6362, 67, 70, 4009, 74, 14463, 5646, 63, 77, 13563, 273, 389, 8949, 87, 63, 2 ]
pragma solidity >=0.8.0 <0.9.0; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // Keno game with some hard-coded parameters: // - 80 numbers to choose from // - player selects between 1 and 10 of these // - game draws 20 of the 80 // Hashes // playerRevealHash = hash(playerAddress, salt, choices[10]) - salt should be a random uint256 // playerCommitHash = hash(playerRevealHash) - added to game before the houseHash is known // houseHash: let the house supply any suitably random data as a uint256 - added to game before the playerRevealHash is known // Optimal strategy for both house and player is (I think!) to provide a totally random hash/salt // Randomness // Generated from playerRevealHash and houseHash. // The resulting uint256 has 256 bits of data, only 123 bits needed for 20 choices from 1..80 uint8 constant BLOCKS_BEFORE_CANCEL = 5; uint8 constant BLOCKS_BEFORE_HOUSE_CLAIM = 10; uint8 constant BLOCKS_BEFORE_ANY_CLAIM = 255; contract KovanKeno { enum GameStatus {INITIALISED, CREATED, CANCELLED, FUNDED, PLAYED, CLAIMED} // How much does matching k out of n numbers make per $100? // Rows are n (1..10), columns are k (0..10) // would have preferred doubly nested array, but Solidity didn't seem to like it... uint256[110] public payoutsPer100_flat = [ 0, 380, 0, 0, 0, 0, 0, 0, 0, 0, 0, // n = 1 choices, k = 0 to 10 matches (2 to 10 not possible, so zero) 0, 110, 880, 0, 0, 0, 0, 0, 0, 0, 0, // n = 2 0, 0, 288, 4000, 0, 0, 0, 0, 0, 0, 0, // n = 3 0, 0, 130, 700, 12000, 0, 0, 0, 0, 0, 0, // n = 4 0, 0, 0, 300, 2500, 60000, 0, 0, 0, 0, 0, // n = 5 0, 0, 0, 168, 800, 8000, 200000, 0, 0, 0, 0, // n = 6 200, 0, 0, 0, 200, 1800, 28000, 1000000, 0, 0, 0, // n = 7 300, 0, 0, 0, 200, 800, 5000, 80000, 3000000, 0, 0, // n = 8 400, 0, 0, 0, 0, 400, 2500, 32000, 500000, 10000000, 0, // n = 9 600, 0, 0, 0, 0, 200, 1000, 10000, 115000, 2000000, 20000000 // n = 10 choices, payouts for k = 0 to 10 matches (11 data points) ]; // For each n, what is the maximum payout per $100 the house must make available? uint256[10] public payoutsPer100_max = [ // idx = n-1 here 380, 880, 4000, 12000, 60000, 200000, 1000000, 3000000, 10000000, 20000000 ]; function getPayoutPer100(uint8 k, uint8 n) public view returns (uint256) { // n in range 1 to 10 (number of choices) // k in range 0 to 10 (number of matches) uint8 idx = k + 11 * (n - 1); // index in flat array above return payoutsPer100_flat[idx]; } function getMaxPayoutPer100(uint8 n) public view returns(uint256) { // n in range 1 to 10 (number of choices) uint8 idx = n - 1; // index in max array above return payoutsPer100_max[idx]; } // Store data for individual game struct KenoGame { GameStatus status; // Status of game uint256 currentValue; // keep track of amount in the game uint256 blockNumCreated; // Block number the game was created address playerAddress; // Address of player uint256 playerValue; // Amount the player bet bytes32 playerCommitHash; // Commit hash of player upon creation of game uint8 choiceCount; // between 1 and 10; number of choices (known when creating game and committing) uint8[10] choices; // numbers between 1 and 80; (only known after revealing) uint256 blockNumFunded; // Block number the game was funded address houseAddress; // Address of house bytes32 houseHash; // random data contribution from house uint8[20] results; // 20 distinct numbers between 1 and 80, derived from playerRevealHash and houseHash uint8[10] matches; // between 1 and 10 numbers that matched } // Easily initialise a new game function getNewKenoGame() private pure returns (KenoGame memory) { return KenoGame({ status: GameStatus.INITIALISED, currentValue: 0, blockNumCreated: 0, playerAddress: address(0), playerValue: 0, playerCommitHash: 0, choiceCount: 0, choices: [0,0,0,0,0, 0,0,0,0,0], blockNumFunded: 0, houseAddress: address(0), houseHash: 0, results: [0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0], matches: [0,0,0,0,0, 0,0,0,0,0] }); } uint256 public nextGameIndex = 0; KenoGame[] public games; uint256 public totalValueInContract = 0; constructor() { // is there anything to do on deploy? } function incrementGameValue(KenoGame memory game, uint256 value) private { totalValueInContract += value; game.currentValue += value; } function decrementGameValue(KenoGame memory game, uint256 value) private { totalValueInContract -= value; game.currentValue -= value; } // Create a game with a specific number of choices and specific commitHash // Construct commitHash using functions getRevealHash then getCommitHash // Will need a random salt value, and remember it to playGame later function createGame(uint8 choiceCount, bytes32 commitHash) public payable returns (uint256) { uint256 blockNum = block.number; uint256 value = msg.value; address playerAddress = msg.sender; // Checks require(0 < value, "No money was sent"); require(0 < choiceCount, "Must make at least 1 choice"); require(choiceCount <= 10, "Maximum choices is 10"); // Construct new game and add to contract KenoGame memory game = getNewKenoGame(); game.status = GameStatus.CREATED; game.blockNumCreated = blockNum; incrementGameValue(game, value); game.playerValue += value; game.playerAddress = playerAddress; game.playerCommitHash = commitHash; game.choiceCount = choiceCount; // Add new game to contract games.push(game); uint256 gameIndex = nextGameIndex; nextGameIndex += 1; // Return index of the new game return gameIndex; } // Get game from memory, throw user-friendly error if out of bounds function getGame(uint256 gameIndex) public view returns (KenoGame memory) { require (gameIndex < nextGameIndex, "Game does not exist"); return games[gameIndex]; } // Need to call this at end of each function // after updates, before any payments function storeUpdatedGame(KenoGame memory game, uint256 index) private { games[index] = game; } // If game does not get funded within BLOCKS_BEFORE_CANCEL blocks, // player can cancel and get full refund function cancelGame(uint256 gameIndex) public { uint256 blockNum = block.number; address playerAddress = msg.sender; KenoGame memory game = getGame(gameIndex); // Checks require(game.playerAddress == playerAddress, "Only player can cancel the game"); require(game.status == GameStatus.CREATED, "Game must be created but not funded"); require(BLOCKS_BEFORE_CANCEL < blockNum - game.blockNumCreated, "Game cannot be cancelled yet"); // Refund player the money uint256 refundAmount = game.currentValue; game.status = GameStatus.CANCELLED; decrementGameValue(game, refundAmount); storeUpdatedGame(game, gameIndex); (bool sent, ) = playerAddress.call{value: refundAmount}(""); require(sent, "Failed to refund player"); } // Easily find out game status function getGameStatus(uint256 gameIndex) public view returns (GameStatus) { KenoGame memory game = getGame(gameIndex); return game.status; } // Easily find out how much funding the house must provide for a specific game function getGameFundingNeeded(uint256 gameIndex) public view returns (uint256) { KenoGame memory game = getGame(gameIndex); uint8 choiceCount = game.choiceCount; // n require(1 <= choiceCount && choiceCount <= 10, "Game choice count is not valid"); uint256 maxPayoutPer100 = getMaxPayoutPer100(choiceCount); uint256 fundingNeeded = (game.playerValue * maxPayoutPer100) / 100; return fundingNeeded; } // House should call this to fund a game, within BLOCKS_BEFORE_CANCEL blocks of player creating the game // Send a decent chunk of "msg.value" to fund // Use getGameFundingNeeded to find out how much // Supply a random seed houseHash that player must include to generate randomness // (e.g. player does not know houseHash when creating, // and house does not know playerRevealHash when funding) function fundGame(uint256 gameIndex, bytes32 houseHash) public payable { uint256 blockNum = block.number; uint256 value = msg.value; address houseAddress = msg.sender; KenoGame memory game = getGame(gameIndex); // Checks require(game.status == GameStatus.CREATED, "Game must be created but not funded"); require(game.blockNumCreated < blockNum, "Must fund game in a later block to game creation"); require(blockNum - game.blockNumCreated <= BLOCKS_BEFORE_CANCEL, "Must fund game within a few blocks of game creation"); uint256 fundingNeeded = getGameFundingNeeded(gameIndex); require(fundingNeeded == value, "Funding amount is wrong"); // Update game as funded game.status = GameStatus.FUNDED; game.blockNumFunded = blockNum; incrementGameValue(game, value); game.houseAddress = houseAddress; game.houseHash = houseHash; storeUpdatedGame(game, gameIndex); } // Check that an array of player choices is valid function validateAndCountChoices(uint8[10] memory choices) public pure returns (bool, uint8) { // Supply an array of choices as strictly ascending numbers between 1 and 80 // There must be between 1 and 10 choices // Unused entries must be at the end, and they must be 0 // Example valid choices: // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] returns (true, 10) // [45, 79, 0, 0, 0, 0, 0, 0, 0, 0] returns (true, 2) // Example invalid choices: // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // [2, 1, 3, 4, 5, 6, 7, 8, 9, 10] // [1, 2, 3, 4, 0, 0, 5, 6, 0, 0] // Invalid choices all return (false, 0) uint8 choiceCount = 0; uint8 prevValue = 0; // Check the non-zero choices are ascending and in range. Also count them. for (uint8 i = 0; i < 10; i++) { uint8 thisValue = choices[i]; if (thisValue == 0) break; if (prevValue < thisValue && thisValue <= 80) { choiceCount += 1; prevValue = thisValue; } else { // choice is either not greater than previous value, or greater than 80 return (false, 0); } } // Check the rest of the choice array is zeros for (uint8 i = choiceCount; i < 10; i++) { if (choices[i] != 0) return (false, 0); } if (choiceCount == 0) return (false, 0); return (true, choiceCount); } // Helper functions for hashing and randomness function getRevealHash(address theAddress, bytes32 randomSalt, uint8[10] memory choices) public pure returns (bytes32) { return keccak256(abi.encodePacked(theAddress, randomSalt, choices)); } function getCommitHash(bytes32 revealHash) public pure returns (bytes32) { return keccak256(abi.encodePacked(revealHash)); } function getRandomHash(bytes32 playerHash, bytes32 houseHash) public pure returns (bytes32) { return keccak256(abi.encodePacked(playerHash, houseHash)); } function getRandomComponent(uint256 initNum, uint8 limit) public pure returns (uint8 modNum, uint256 resNum) { modNum = uint8(initNum % limit); resNum = (initNum - modNum) / limit; return (modNum, resNum); } // Player uses this to reveal their choices in a specific game (along with the salt) // which can be verified using their commitHash // Game will either be won or lost depending on a random draw of 20 numbers from 80, // according to randomness generated from revealHash and houseHash // Player MUST call this within BLOCKS_BEFORE_HOUSE_CLAIM blocks of game being funded, // otherwise house can claim all funds in the game! function playGame(uint256 gameIndex, bytes32 saltUsed, uint8[10] memory choices) public { address playerAddress = msg.sender; KenoGame memory game = getGame(gameIndex); // General checks require(game.playerAddress == playerAddress, "Game must be played by same player who created it"); require(game.status == GameStatus.FUNDED, "Game must be funded before playing"); // Check commit hash matches bytes32 revealHash = getRevealHash(playerAddress, saltUsed, choices); bytes32 commitHash = getCommitHash(revealHash); require(commitHash == game.playerCommitHash, "Failed to play game, commit hash mismatch"); // Check choices are valid (bool choicesValid, uint8 choiceCount) = validateAndCountChoices(choices); require(choicesValid, "Player choice list is invalid. Player forfeits game."); require(game.choiceCount == choiceCount, "Player choice list is the wrong length. Player forfeits game."); game.choices = choices; // Play the game! // Calculate 20 numbers from 80 at random uint256 init = uint256(getRandomHash(revealHash, game.houseHash)); // this initial value contains 256 bits of information // to select 20 numbers from 1 to 80, require 122.69 bits of information // can therefore use this one 256-bit number to get all the choices uint8 idx = 0; uint8[80] memory remainingNumbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 ]; for (uint8 i = 0; i < 20; i++) { (idx, init) = getRandomComponent(init, 80-i); // for i=0, idx will be in range 0 to 79 game.results[i] = remainingNumbers[idx]; remainingNumbers[idx] = remainingNumbers[80-i-1]; // quick and lazy shortening of array! } // Find the matching numbers; store and count them uint8 matchCount = 0; for (uint8 i = 0; i < game.choiceCount; i++) { uint8 num = game.choices[i]; for (uint8 j = 0; j < 20; j++) { if (num == game.results[j]) { game.matches[matchCount] = num; matchCount += 1; } } } // Calculate the player's winnings, and withdraw to player game.status = GameStatus.PLAYED; uint256 playerWinnings = (game.playerValue * getPayoutPer100(matchCount, choiceCount)) / 100; decrementGameValue(game, playerWinnings); storeUpdatedGame(game, gameIndex); if (0 < playerWinnings) { (bool sent, ) = playerAddress.call{value: playerWinnings}(""); require(sent, "Failed to withdraw player's funds"); } else { // player is a loser, no withdraw for you! ;) } // The remainder of game funds is due to the house now // Do this in a separate claimGameFunds call by the house } // Function to allow any remaining funds in a game to be withdrawn // by firstly the house, and failing that (after a while), anyone function claimGameFunds(uint256 gameIndex) public { uint256 blockNum = block.number; address claimerAddress = msg.sender; KenoGame memory game = getGame(gameIndex); // Checks require(0 < game.currentValue, "Game has no funds left in it"); bool claimerIsHouse = (claimerAddress == game.houseAddress); bool fundedAWhileAgo = (0 < game.blockNumFunded) && (BLOCKS_BEFORE_HOUSE_CLAIM < blockNum - game.blockNumFunded); bool createdAVeryLongTimeAgo = (0 < game.blockNumCreated) && (BLOCKS_BEFORE_ANY_CLAIM < blockNum - game.blockNumCreated); // Who can claim remaining funds? // 1. House can claim immediately after player has played // 2. House can claim on delay after funding (e.g. if player fails to play, perhaps knowing they lose) // 3. If house fails to claim for a long time, ANYONE can withdraw the funds :) require( (game.status == GameStatus.PLAYED && claimerIsHouse) || (game.status == GameStatus.FUNDED && claimerIsHouse && fundedAWhileAgo) || createdAVeryLongTimeAgo , "Conditions for claiming game are not met yet"); // Allow withdrawal to claimer uint256 withdrawalAmount = game.currentValue; game.status = GameStatus.CLAIMED; decrementGameValue(game, withdrawalAmount); storeUpdatedGame(game, gameIndex); (bool sent, ) = claimerAddress.call{value: withdrawalAmount}(""); require(sent, "Failed to withdraw funds to claimer"); } }
Player uses this to reveal their choices in a specific game (along with the salt) which can be verified using their commitHash Game will either be won or lost depending on a random draw of 20 numbers from 80, according to randomness generated from revealHash and houseHash Player MUST call this within BLOCKS_BEFORE_HOUSE_CLAIM blocks of game being funded, otherwise house can claim all funds in the game! General checks Check commit hash matches Check choices are valid Play the game! Calculate 20 numbers from 80 at random this initial value contains 256 bits of information to select 20 numbers from 1 to 80, require 122.69 bits of information can therefore use this one 256-bit number to get all the choices player is a loser, no withdraw for you! ;)
function playGame(uint256 gameIndex, bytes32 saltUsed, uint8[10] memory choices) public { address playerAddress = msg.sender; KenoGame memory game = getGame(gameIndex); require(game.playerAddress == playerAddress, "Game must be played by same player who created it"); require(game.status == GameStatus.FUNDED, "Game must be funded before playing"); bytes32 revealHash = getRevealHash(playerAddress, saltUsed, choices); bytes32 commitHash = getCommitHash(revealHash); require(commitHash == game.playerCommitHash, "Failed to play game, commit hash mismatch"); (bool choicesValid, uint8 choiceCount) = validateAndCountChoices(choices); require(choicesValid, "Player choice list is invalid. Player forfeits game."); require(game.choiceCount == choiceCount, "Player choice list is the wrong length. Player forfeits game."); game.choices = choices; uint256 init = uint256(getRandomHash(revealHash, game.houseHash)); uint8 idx = 0; uint8[80] memory remainingNumbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 ]; for (uint8 i = 0; i < 20; i++) { game.results[i] = remainingNumbers[idx]; } for (uint8 i = 0; i < game.choiceCount; i++) { uint8 num = game.choices[i]; for (uint8 j = 0; j < 20; j++) { if (num == game.results[j]) { game.matches[matchCount] = num; matchCount += 1; } } } uint256 playerWinnings = (game.playerValue * getPayoutPer100(matchCount, choiceCount)) / 100; decrementGameValue(game, playerWinnings); storeUpdatedGame(game, gameIndex); if (0 < playerWinnings) { require(sent, "Failed to withdraw player's funds"); }
13,053,401
[ 1, 12148, 4692, 333, 358, 283, 24293, 3675, 7246, 316, 279, 2923, 7920, 261, 287, 932, 598, 326, 4286, 13, 1492, 848, 506, 13808, 1450, 3675, 3294, 2310, 14121, 903, 3344, 506, 8462, 578, 13557, 8353, 603, 279, 2744, 3724, 434, 4200, 5600, 628, 8958, 16, 4888, 358, 2744, 4496, 4374, 628, 283, 24293, 2310, 471, 23867, 2310, 19185, 10685, 745, 333, 3470, 14073, 55, 67, 19152, 67, 7995, 8001, 67, 15961, 3445, 4398, 434, 7920, 3832, 9831, 785, 16, 3541, 23867, 848, 7516, 777, 284, 19156, 316, 326, 7920, 5, 9544, 4271, 2073, 3294, 1651, 1885, 2073, 7246, 854, 923, 19592, 326, 7920, 5, 9029, 4200, 5600, 628, 8958, 622, 2744, 333, 2172, 460, 1914, 8303, 4125, 434, 1779, 358, 2027, 4200, 5600, 628, 404, 358, 8958, 16, 2583, 31501, 18, 8148, 4125, 434, 1779, 848, 13526, 999, 333, 1245, 8303, 17, 3682, 1300, 358, 336, 777, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 6599, 12496, 12, 11890, 5034, 7920, 1016, 16, 1731, 1578, 4286, 6668, 16, 2254, 28, 63, 2163, 65, 3778, 7246, 13, 1071, 288, 203, 565, 1758, 7291, 1887, 273, 1234, 18, 15330, 31, 203, 565, 1475, 5764, 12496, 3778, 7920, 273, 7162, 339, 12, 13957, 1016, 1769, 203, 565, 2583, 12, 13957, 18, 14872, 1887, 422, 7291, 1887, 16, 315, 12496, 1297, 506, 6599, 329, 635, 1967, 7291, 10354, 2522, 518, 8863, 203, 565, 2583, 12, 13957, 18, 2327, 422, 14121, 1482, 18, 42, 2124, 7660, 16, 315, 12496, 1297, 506, 9831, 785, 1865, 23982, 8863, 203, 565, 1731, 1578, 283, 24293, 2310, 273, 5561, 24293, 2310, 12, 14872, 1887, 16, 4286, 6668, 16, 7246, 1769, 203, 565, 1731, 1578, 3294, 2310, 273, 336, 5580, 2310, 12, 266, 24293, 2310, 1769, 203, 565, 2583, 12, 7371, 2310, 422, 7920, 18, 14872, 5580, 2310, 16, 315, 2925, 358, 6599, 7920, 16, 3294, 1651, 13484, 8863, 203, 565, 261, 6430, 7246, 1556, 16, 2254, 28, 6023, 1380, 13, 273, 1954, 1876, 1380, 17442, 12, 11937, 1769, 203, 565, 2583, 12, 11937, 1556, 16, 315, 12148, 6023, 666, 353, 2057, 18, 19185, 364, 3030, 1282, 7920, 1199, 1769, 203, 565, 2583, 12, 13957, 18, 11569, 1380, 422, 6023, 1380, 16, 315, 12148, 6023, 666, 353, 326, 7194, 769, 18, 19185, 364, 3030, 1282, 7920, 1199, 1769, 203, 565, 7920, 18, 11937, 273, 7246, 31, 203, 565, 2254, 5034, 1208, 273, 2254, 5034, 12, 588, 8529, 2310, 12, 266, 24293, 2310, 16, 7920, 18, 13028, 2310, 2 ]
./full_match/1/0x261881b557e2eE82DA689576B04e3f7Ad8E651c9/sources/cache/solpp-generated-contracts/common/L2ContractHelper.sol
A contract that is allowed to deploy any codehash on any address. To be used only during an upgrade.
library L2ContractHelper { bytes32 constant CREATE2_PREFIX = keccak256("zksyncCreate2"); function forceDeployOnAddresses(ForceDeployment[] calldata _deployParams) external; function create2( bytes32 _salt, bytes32 _bytecodeHash, bytes calldata _input ) external; } address constant BOOTLOADER_ADDRESS = address(SYSTEM_CONTRACTS_OFFSET + 0x01); address constant DEPLOYER_SYSTEM_CONTRACT_ADDRESS = address(SYSTEM_CONTRACTS_OFFSET + 0x06); address constant FORCE_DEPLOYER = address(SYSTEM_CONTRACTS_OFFSET + 0x07); IL2Messenger constant L2_MESSENGER = IL2Messenger(address(SYSTEM_CONTRACTS_OFFSET + 0x08)); address constant VALUE_SIMULATOR_SYSTEM_CONTRACT_ADDRESS = address(SYSTEM_CONTRACTS_OFFSET + 0x09); function sendMessageToL1(bytes memory _message) internal returns (bytes32) { return L2_MESSENGER.sendToL1(_message); } function hashL2Bytecode(bytes memory _bytecode) internal pure returns (bytes32 hashedBytecode) { require(_bytecode.length % 32 == 0, "po"); uint256 bytecodeLenInWords = _bytecode.length / 32; hashedBytecode = sha256(_bytecode) & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; hashedBytecode = (hashedBytecode | bytes32(uint256(1 << 248))); hashedBytecode = hashedBytecode | bytes32(bytecodeLenInWords << 224); } function validateBytecodeHash(bytes32 _bytecodeHash) internal pure { uint8 version = uint8(_bytecodeHash[0]); } function bytecodeLen(bytes32 _bytecodeHash) internal pure returns (uint256 codeLengthInWords) { codeLengthInWords = uint256(uint8(_bytecodeHash[2])) * 256 + uint256(uint8(_bytecodeHash[3])); } function computeCreate2Address( address _sender, bytes32 _salt, bytes32 _bytecodeHash, bytes32 _constructorInputHash ) internal pure returns (address) { bytes32 senderBytes = bytes32(uint256(uint160(_sender))); bytes32 data = keccak256( bytes.concat(CREATE2_PREFIX, senderBytes, _salt, _bytecodeHash, _constructorInputHash) ); return address(uint160(uint256(data))); } }
17,015,485
[ 1, 37, 6835, 716, 353, 2935, 358, 7286, 1281, 981, 2816, 603, 1281, 1758, 18, 2974, 506, 1399, 1338, 4982, 392, 8400, 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, 12083, 511, 22, 8924, 2276, 288, 203, 565, 1731, 1578, 5381, 13278, 22, 67, 6307, 273, 417, 24410, 581, 5034, 2932, 94, 7904, 1209, 1684, 22, 8863, 203, 203, 565, 445, 2944, 10015, 1398, 7148, 12, 10997, 6733, 8526, 745, 892, 389, 12411, 1370, 13, 3903, 31, 203, 203, 565, 445, 752, 22, 12, 203, 3639, 1731, 1578, 389, 5759, 16, 203, 3639, 1731, 1578, 389, 1637, 16651, 2310, 16, 203, 3639, 1731, 745, 892, 389, 2630, 203, 565, 262, 3903, 31, 203, 97, 203, 203, 203, 2867, 5381, 9784, 1974, 1502, 5483, 67, 15140, 273, 1758, 12, 14318, 67, 6067, 2849, 1268, 55, 67, 11271, 397, 374, 92, 1611, 1769, 203, 203, 2867, 5381, 2030, 22971, 654, 67, 14318, 67, 6067, 2849, 1268, 67, 15140, 273, 1758, 12, 14318, 67, 6067, 2849, 1268, 55, 67, 11271, 397, 374, 92, 7677, 1769, 203, 203, 2867, 5381, 12108, 1441, 67, 1639, 22971, 654, 273, 1758, 12, 14318, 67, 6067, 2849, 1268, 55, 67, 11271, 397, 374, 92, 8642, 1769, 203, 203, 2627, 22, 29329, 5381, 511, 22, 67, 958, 12130, 50, 3101, 273, 467, 48, 22, 29329, 12, 2867, 12, 14318, 67, 6067, 2849, 1268, 55, 67, 11271, 397, 374, 92, 6840, 10019, 203, 203, 2867, 5381, 5848, 67, 2320, 49, 1506, 3575, 67, 14318, 67, 6067, 2849, 1268, 67, 15140, 273, 1758, 12, 14318, 67, 6067, 2849, 1268, 55, 67, 11271, 397, 374, 92, 5908, 1769, 203, 203, 565, 445, 15399, 774, 48, 21, 12, 3890, 3778, 389, 2150, 13, 2713, 1135, 261, 3890, 2 ]
pragma solidity 0.6.5; import "./Admin.sol"; contract SuperOperators is Admin { mapping(address => bool) internal _superOperators; event SuperOperator(address superOperator, bool enabled); /// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). /// @param superOperator address that will be given/removed superOperator right. /// @param enabled set whether the superOperator is enabled or disabled. function setSuperOperator(address superOperator, bool enabled) external { require(msg.sender == _admin, "only admin is allowed to add super operators"); _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); } /// @notice check whether address `who` is given superOperator rights. /// @param who The address to query. /// @return whether the address has superOperator rights. function isSuperOperator(address who) public view returns (bool) { return _superOperators[who]; } }
@notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). @param superOperator address that will be given/removed superOperator right. @param enabled set whether the superOperator is enabled or disabled.
function setSuperOperator(address superOperator, bool enabled) external { require(msg.sender == _admin, "only admin is allowed to add super operators"); _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); }
5,405,883
[ 1, 8317, 578, 4056, 326, 7123, 434, 1375, 9565, 5592, 68, 358, 7412, 2430, 434, 777, 261, 9565, 5592, 14989, 2934, 225, 2240, 5592, 1758, 716, 903, 506, 864, 19, 14923, 2240, 5592, 2145, 18, 225, 3696, 444, 2856, 326, 2240, 5592, 353, 3696, 578, 5673, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 8051, 5592, 12, 2867, 2240, 5592, 16, 1426, 3696, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 3666, 16, 315, 3700, 3981, 353, 2935, 358, 527, 2240, 12213, 8863, 203, 3639, 389, 9565, 24473, 63, 9565, 5592, 65, 273, 3696, 31, 203, 3639, 3626, 14845, 5592, 12, 9565, 5592, 16, 3696, 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 ]
./full_match/44787/0xB02f7eAFFA2159E03476ffb4317008Aa691e4B39/sources/project_/contracts/VirtuousMarket.sol
cUSD stable contract address
contract VirtuousMarket is ERC721Enumerable, ERC721URIStorage, Pausable, Ownable, ReentrancyGuard { using Math for uint256; using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; using SafeERC20 for IERC20; address private cUSD = 0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1; pragma solidity ^0.8.4; struct ResellNFT { uint256 salePrice; uint saleStatus; } mapping(uint256 => ResellNFT) private tokenResellInfo; mapping(uint256 => address) private tokenBeneficiary; event ResellListed(uint256 tokenId, uint256 salePrice); event PurchasedNFT(uint256 tokenId, address from, address to, uint256 salePrice); constructor() ERC721("Virtuous Market", "VM") {} function _baseURI() internal pure override returns (string memory) { } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function etherToWei(uint valueEther) internal pure returns (uint) { return valueEther*(10**18); } function getTokenResellInfo(uint256 _tokenId) external view returns (ResellNFT memory) { ResellNFT memory resell = tokenResellInfo[_tokenId]; return resell; } function getTokenBeneficiary(uint256 _tokenId) external view returns (address beneficiary) { return tokenBeneficiary[_tokenId]; } function safeMint(address to, string memory uri, address beneficiary) external onlyOwner nonReentrant returns (uint256){ _tokenIdCounter.increment(); uint256 tokenId = _tokenIdCounter.current(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri); tokenBeneficiary[tokenId] = beneficiary; return tokenId; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function resellNFD(uint256 _tokenId, uint256 _salePrice) external whenNotPaused nonReentrant { require( ownerOf(_tokenId) == _msgSender(), 'You are not the owner of this token!'); ResellNFT memory resell = tokenResellInfo[_tokenId]; require(resell.saleStatus == 0, 'This Token is already listed for resell!'); approve(address(this), _tokenId); tokenResellInfo[_tokenId] = ResellNFT(_salePrice, 1); emit ResellListed(_tokenId, _salePrice); } function purchaseNFD(uint256 _tokenId, uint256 _amount) external whenNotPaused nonReentrant { address buyer = _msgSender(); require( ownerOf(_tokenId) != buyer, 'Token Owner can not purchase own token!'); ResellNFT memory resell = tokenResellInfo[_tokenId]; require(resell.saleStatus == 1, 'This Token is not listed for resell!'); uint256 saleFee = resell.salePrice.div(100).mul(10); uint256 salePriceWithFee = resell.salePrice.add(saleFee); require(_amount >= salePriceWithFee, 'Purchase value can not be less than of sale value with 10% fee!'); require(IERC20(cUSD).balanceOf(buyer) >= etherToWei(salePriceWithFee), 'Insufficiant ERC20 token balance!'); require(IERC20(cUSD).allowance(buyer, address(this)) >= etherToWei(salePriceWithFee), 'Approve ERC20 tokens first!'); IERC20(cUSD).safeTransferFrom(buyer, ownerOf(_tokenId), etherToWei(_amount)); uint256 marketplaceRoyaltyFee = saleFee.div(100).mul(2); IERC20(cUSD).safeTransferFrom(buyer, owner(), etherToWei(marketplaceRoyaltyFee)); uint256 beneficiaryRoyaltyFee = saleFee.sub(marketplaceRoyaltyFee); IERC20(cUSD).safeTransferFrom(buyer, tokenBeneficiary[_tokenId], etherToWei(beneficiaryRoyaltyFee)); safeTransferFrom(ownerOf(_tokenId), buyer, _tokenId); tokenResellInfo[_tokenId] = ResellNFT(salePriceWithFee, 0); emit PurchasedNFT(_tokenId, ownerOf(_tokenId), buyer, salePriceWithFee); } }
13,242,455
[ 1, 71, 3378, 40, 14114, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 776, 2714, 89, 1481, 3882, 278, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 4232, 39, 27, 5340, 3098, 3245, 16, 21800, 16665, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 203, 565, 1450, 2361, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 548, 4789, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1758, 3238, 276, 3378, 40, 273, 374, 92, 28, 5608, 7677, 29, 29634, 21, 41, 70, 2313, 40, 6334, 72, 26, 3787, 42, 22, 73, 20, 23508, 2947, 1340, 37, 4033, 4366, 8148, 70, 39, 21, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 1958, 1124, 1165, 50, 4464, 288, 203, 3639, 2254, 5034, 272, 5349, 5147, 31, 203, 3639, 2254, 272, 5349, 1482, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1124, 1165, 50, 4464, 13, 3238, 1147, 607, 1165, 966, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 1147, 38, 4009, 74, 14463, 814, 31, 203, 203, 565, 871, 1124, 1165, 682, 329, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 272, 5349, 5147, 1769, 203, 565, 871, 14466, 343, 8905, 50, 4464, 12, 11890, 5034, 1147, 548, 16, 1758, 628, 16, 1758, 358, 16, 2254, 5034, 272, 5349, 5147, 1769, 203, 203, 203, 565, 3885, 1435, 2 ]
./partial_match/1/0x11D635bbba3f9B8f7C9b91cA9f315a2207cb5AD5/sources/dHealthToken.sol
* @dev Default fallback method which will be called when any ethers are sent to contract/
function() public payable { buy(msg.sender); }
9,236,477
[ 1, 1868, 5922, 707, 1492, 903, 506, 2566, 1347, 1281, 13750, 414, 854, 3271, 358, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1435, 1071, 8843, 429, 288, 203, 202, 202, 70, 9835, 12, 3576, 18, 15330, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { IExtension } from "../interfaces/IExtension.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { MutualUpgrade } from "../lib/MutualUpgrade.sol"; /** * @title BaseManagerV2 * @author Set Protocol * * Smart contract manager that contains permissions and admin functionality. Implements IIP-64, supporting * a registry of protected modules that can only be upgraded with methodologist consent. */ contract BaseManagerV2 is MutualUpgrade { using Address for address; using AddressArrayUtils for address[]; using SafeERC20 for IERC20; /* ============ Struct ========== */ struct ProtectedModule { bool isProtected; // Flag set to true if module is protected address[] authorizedExtensionsList; // List of Extensions authorized to call module mapping(address => bool) authorizedExtensions; // Map of extensions authorized to call module } /* ============ Events ============ */ event ExtensionAdded( address _extension ); event ExtensionRemoved( address _extension ); event MethodologistChanged( address _oldMethodologist, address _newMethodologist ); event OperatorChanged( address _oldOperator, address _newOperator ); event ExtensionAuthorized( address _module, address _extension ); event ExtensionAuthorizationRevoked( address _module, address _extension ); event ModuleProtected( address _module, address[] _extensions ); event ModuleUnprotected( address _module ); event ReplacedProtectedModule( address _oldModule, address _newModule, address[] _newExtensions ); event EmergencyReplacedProtectedModule( address _module, address[] _extensions ); event EmergencyRemovedProtectedModule( address _module ); event EmergencyResolved(); /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken operator */ modifier onlyOperator() { require(msg.sender == operator, "Must be operator"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist() { require(msg.sender == methodologist, "Must be methodologist"); _; } /** * Throws if the sender is not a listed extension */ modifier onlyExtension() { require(isExtension[msg.sender], "Must be extension"); _; } /** * Throws if contract is in an emergency state following a unilateral operator removal of a * protected module. */ modifier upgradesPermitted() { require(emergencies == 0, "Upgrades paused by emergency"); _; } /** * Throws if contract is *not* in an emergency state. Emergency replacement and resolution * can only happen in an emergency */ modifier onlyEmergency() { require(emergencies > 0, "Not in emergency"); _; } /* ============ State Variables ============ */ // Instance of SetToken ISetToken public setToken; // Array of listed extensions address[] internal extensions; // Mapping to check if extension is added mapping(address => bool) public isExtension; // Address of operator which typically executes manager only functions on Set Protocol modules address public operator; // Address of methodologist which serves as providing methodology for the index address public methodologist; // Counter incremented when the operator "emergency removes" a protected module. Decremented // when methodologist executes an "emergency replacement". Operator can only add modules and // extensions when `emergencies` is zero. Emergencies can only be declared "over" by mutual agreement // between operator and methodologist or by the methodologist alone via `resolveEmergency` uint256 public emergencies; // Mapping of protected modules. These cannot be called or removed except by mutual upgrade. mapping(address => ProtectedModule) public protectedModules; // List of protected modules, for iteration. Used when checking that an extension removal // can happen without methodologist approval address[] public protectedModulesList; // Boolean set when methodologist authorizes initialization after contract deployment. // Must be true to call via `interactManager`. bool public initialized; /* ============ Constructor ============ */ constructor( ISetToken _setToken, address _operator, address _methodologist ) public { setToken = _setToken; operator = _operator; methodologist = _methodologist; } /* ============ External Functions ============ */ /** * ONLY METHODOLOGIST : Called by the methodologist to enable contract. All `interactManager` * calls revert until this is invoked. Lets methodologist review and authorize initial protected * module settings. */ function authorizeInitialization() external onlyMethodologist { require(!initialized, "Initialization authorized"); initialized = true; } /** * MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call * this function to execute the update. * * @param _newManager New manager address */ function setManager(address _newManager) external mutualUpgrade(operator, methodologist) { require(_newManager != address(0), "Zero address not valid"); setToken.setManager(_newManager); } /** * OPERATOR ONLY: Add a new extension that the BaseManager can call. * * @param _extension New extension to add */ function addExtension(address _extension) external upgradesPermitted onlyOperator { require(!isExtension[_extension], "Extension already exists"); require(address(IExtension(_extension).manager()) == address(this), "Extension manager invalid"); _addExtension(_extension); } /** * OPERATOR ONLY: Remove an existing extension tracked by the BaseManager. * * @param _extension Old extension to remove */ function removeExtension(address _extension) external onlyOperator { require(isExtension[_extension], "Extension does not exist"); require(!_isAuthorizedExtension(_extension), "Extension used by protected module"); extensions.removeStorage(_extension); isExtension[_extension] = false; emit ExtensionRemoved(_extension); } /** * MUTUAL UPGRADE: Authorizes an extension for a protected module. Operator and Methodologist must * each call this function to execute the update. Adds extension to manager if not already present. * * @param _module Module to authorize extension for * @param _extension Extension to authorize for module */ function authorizeExtension(address _module, address _extension) external mutualUpgrade(operator, methodologist) { require(protectedModules[_module].isProtected, "Module not protected"); require(!protectedModules[_module].authorizedExtensions[_extension], "Extension already authorized"); _authorizeExtension(_module, _extension); emit ExtensionAuthorized(_module, _extension); } /** * MUTUAL UPGRADE: Revokes extension authorization for a protected module. Operator and Methodologist * must each call this function to execute the update. In order to remove the extension completely * from the contract removeExtension must be called by the operator. * * @param _module Module to revoke extension authorization for * @param _extension Extension to revoke authorization of */ function revokeExtensionAuthorization(address _module, address _extension) external mutualUpgrade(operator, methodologist) { require(protectedModules[_module].isProtected, "Module not protected"); require(isExtension[_extension], "Extension does not exist"); require(protectedModules[_module].authorizedExtensions[_extension], "Extension not authorized"); protectedModules[_module].authorizedExtensions[_extension] = false; protectedModules[_module].authorizedExtensionsList.removeStorage(_extension); emit ExtensionAuthorizationRevoked(_module, _extension); } /** * ADAPTER ONLY: Interact with a module registered on the SetToken. Manager initialization must * have been authorized by methodologist. Extension making this call must be authorized * to call module if module is protected. * * @param _module Module to interact with * @param _data Byte data of function to call in module */ function interactManager(address _module, bytes memory _data) external onlyExtension { require(initialized, "Manager not initialized"); require(_module != address(setToken), "Extensions cannot call SetToken"); require(_senderAuthorizedForModule(_module, msg.sender), "Extension not authorized for module"); // Invoke call to module, assume value will always be 0 _module.functionCallWithValue(_data, 0); } /** * OPERATOR ONLY: Transfers _tokens held by the manager to _destination. Can be used to * recover anything sent here accidentally. In BaseManagerV2, extensions should * be the only contracts designated as `feeRecipient` in fee modules. * * @param _token ERC20 token to send * @param _destination Address receiving the tokens * @param _amount Quantity of tokens to send */ function transferTokens(address _token, address _destination, uint256 _amount) external onlyExtension { IERC20(_token).safeTransfer(_destination, _amount); } /** * OPERATOR ONLY: Add a new module to the SetToken. * * @param _module New module to add */ function addModule(address _module) external upgradesPermitted onlyOperator { setToken.addModule(_module); } /** * OPERATOR ONLY: Remove a new module from the SetToken. Any extensions associated with this * module need to be removed in separate transactions via removeExtension. * * @param _module Module to remove */ function removeModule(address _module) external onlyOperator { require(!protectedModules[_module].isProtected, "Module protected"); setToken.removeModule(_module); } /** * OPERATOR ONLY: Marks a currently protected module as unprotected and deletes its authorized * extension registries. Removes module from the SetToken. Increments the `emergencies` counter, * prohibiting any operator-only module or extension additions until `emergencyReplaceProtectedModule` * is executed or `resolveEmergency` is called by the methodologist. * * Called by operator when a module must be removed immediately for security reasons and it's unsafe * to wait for a `mutualUpgrade` process to play out. * * NOTE: If removing a fee module, you can ensure all fees are distributed by calling distribute * on the module's de-authorized fee extension after this call. * * @param _module Module to remove */ function emergencyRemoveProtectedModule(address _module) external onlyOperator { _unProtectModule(_module); setToken.removeModule(_module); emergencies += 1; emit EmergencyRemovedProtectedModule(_module); } /** * OPERATOR ONLY: Marks an existing module as protected and authorizes extensions for * it, adding them if necessary. Adds module to the protected modules list * * The operator uses this when they're adding new features and want to assure the methodologist * they won't be unilaterally changed in the future. Cannot be called during an emergency because * methodologist needs to explicitly approve protection arrangements under those conditions. * * NOTE: If adding a fee extension while protecting a fee module, it's important to set the * module `feeRecipient` to the new extension's address (ideally before this call). * * @param _module Module to protect * @param _extensions Array of extensions to authorize for protected module */ function protectModule(address _module, address[] memory _extensions) external upgradesPermitted onlyOperator { require(setToken.getModules().contains(_module), "Module not added yet"); _protectModule(_module, _extensions); emit ModuleProtected(_module, _extensions); } /** * METHODOLOGIST ONLY: Marks a currently protected module as unprotected and deletes its authorized * extension registries. Removes old module from the protected modules list. * * Called by the methodologist when they want to cede control over a protected module without triggering * an emergency (for example, to remove it because its dead). * * @param _module Module to revoke protections for */ function unProtectModule(address _module) external onlyMethodologist { _unProtectModule(_module); emit ModuleUnprotected(_module); } /** * MUTUAL UPGRADE: Replaces a protected module. Operator and Methodologist must each call this * function to execute the update. * * > Marks a currently protected module as unprotected * > Deletes its authorized extension registries. * > Removes old module from SetToken. * > Adds new module to SetToken. * > Marks `_newModule` as protected and authorizes new extensions for it. * * Used when methodologists wants to guarantee that an existing protection arrangement is replaced * with a suitable substitute (ex: upgrading a StreamingFeeSplitExtension). * * NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be * the new fee extension address after this call. Any fees remaining in the old module's * de-authorized extensions can be distributed by calling `distribute()` on the old extension. * * @param _oldModule Module to remove * @param _newModule Module to add in place of removed module * @param _newExtensions Extensions to authorize for new module */ function replaceProtectedModule(address _oldModule, address _newModule, address[] memory _newExtensions) external mutualUpgrade(operator, methodologist) { _unProtectModule(_oldModule); setToken.removeModule(_oldModule); setToken.addModule(_newModule); _protectModule(_newModule, _newExtensions); emit ReplacedProtectedModule(_oldModule, _newModule, _newExtensions); } /** * MUTUAL UPGRADE & EMERGENCY ONLY: Replaces a module the operator has removed with * `emergencyRemoveProtectedModule`. Operator and Methodologist must each call this function to * execute the update. * * > Adds new module to SetToken. * > Marks `_newModule` as protected and authorizes new extensions for it. * > Adds `_newModule` to protectedModules list. * > Decrements the emergencies counter, * * Used when methodologist wants to guarantee that a protection arrangement which was * removed in an emergency is replaced with a suitable substitute. Operator's ability to add modules * or extensions is restored after invoking this method (if this is the only emergency.) * * NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be * the new fee extension address after this call. Any fees remaining in the old module's * de-authorized extensions can be distributed by calling `accrueFeesAndDistribute` on the old extension. * * @param _module Module to add in place of removed module * @param _extensions Array of extensions to authorize for replacement module */ function emergencyReplaceProtectedModule( address _module, address[] memory _extensions ) external mutualUpgrade(operator, methodologist) onlyEmergency { setToken.addModule(_module); _protectModule(_module, _extensions); emergencies -= 1; emit EmergencyReplacedProtectedModule(_module, _extensions); } /** * METHODOLOGIST ONLY & EMERGENCY ONLY: Decrements the emergencies counter. * * Allows a methodologist to exit a state of emergency without replacing a protected module that * was removed. This could happen if the module has no viable substitute or operator and methodologist * agree that restoring normal operations is the best way forward. */ function resolveEmergency() external onlyMethodologist onlyEmergency { emergencies -= 1; emit EmergencyResolved(); } /** * METHODOLOGIST ONLY: Update the methodologist address * * @param _newMethodologist New methodologist address */ function setMethodologist(address _newMethodologist) external onlyMethodologist { emit MethodologistChanged(methodologist, _newMethodologist); methodologist = _newMethodologist; } /** * OPERATOR ONLY: Update the operator address * * @param _newOperator New operator address */ function setOperator(address _newOperator) external onlyOperator { emit OperatorChanged(operator, _newOperator); operator = _newOperator; } /* ============ External Getters ============ */ function getExtensions() external view returns(address[] memory) { return extensions; } function getAuthorizedExtensions(address _module) external view returns (address[] memory) { return protectedModules[_module].authorizedExtensionsList; } function isAuthorizedExtension(address _module, address _extension) external view returns (bool) { return protectedModules[_module].authorizedExtensions[_extension]; } function getProtectedModules() external view returns (address[] memory) { return protectedModulesList; } /* ============ Internal ============ */ /** * Add a new extension that the BaseManager can call. */ function _addExtension(address _extension) internal { extensions.push(_extension); isExtension[_extension] = true; emit ExtensionAdded(_extension); } /** * Marks a currently protected module as unprotected and deletes it from authorized extension * registries. Removes module from the SetToken. */ function _unProtectModule(address _module) internal { require(protectedModules[_module].isProtected, "Module not protected"); // Clear mapping and array entries in struct before deleting mapping entry for (uint256 i = 0; i < protectedModules[_module].authorizedExtensionsList.length; i++) { address extension = protectedModules[_module].authorizedExtensionsList[i]; protectedModules[_module].authorizedExtensions[extension] = false; } delete protectedModules[_module]; protectedModulesList.removeStorage(_module); } /** * Adds new module to SetToken. Marks `_newModule` as protected and authorizes * new extensions for it. Adds `_newModule` module to protectedModules list. */ function _protectModule(address _module, address[] memory _extensions) internal { require(!protectedModules[_module].isProtected, "Module already protected"); protectedModules[_module].isProtected = true; protectedModulesList.push(_module); for (uint i = 0; i < _extensions.length; i++) { _authorizeExtension(_module, _extensions[i]); } } /** * Adds extension if not already added and marks extension as authorized for module */ function _authorizeExtension(address _module, address _extension) internal { if (!isExtension[_extension]) { _addExtension(_extension); } protectedModules[_module].authorizedExtensions[_extension] = true; protectedModules[_module].authorizedExtensionsList.push(_extension); } /** * Searches the extension mappings of each protected modules to determine if an extension * is authorized by any of them. Authorized extensions cannot be unilaterally removed by * the operator. */ function _isAuthorizedExtension(address _extension) internal view returns (bool) { for (uint256 i = 0; i < protectedModulesList.length; i++) { if (protectedModules[protectedModulesList[i]].authorizedExtensions[_extension]) { return true; } } return false; } /** * Checks if `_sender` (an extension) is allowed to call a module (which may be protected) */ function _senderAuthorizedForModule(address _module, address _sender) internal view returns (bool) { if (protectedModules[_module].isProtected) { return protectedModules[_module].authorizedExtensions[_sender]; } return true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /* 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; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/27/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IBaseManager } from "./IBaseManager.sol"; interface IExtension { function manager() external view returns (IBaseManager); } 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); } /* Copyright 2018 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 MutualUpgrade * @author Set Protocol * * The MutualUpgrade contract contains a modifier for handling mutual upgrades between two parties */ contract MutualUpgrade { /* ============ State Variables ============ */ // Mapping of upgradable units and if upgrade has been initialized by other party mapping(bytes32 => bool) public mutualUpgrades; /* ============ Events ============ */ event MutualUpgradeRegistered( bytes32 _upgradeHash ); /* ============ Modifiers ============ */ modifier mutualUpgrade(address _signerOne, address _signerTwo) { require( msg.sender == _signerOne || msg.sender == _signerTwo, "Must be authorized address" ); address nonCaller = _getNonCaller(_signerOne, _signerTwo); // The upgrade hash is defined by the hash of the transaction call data and sender of msg, // which uniquely identifies the function, arguments, and sender. bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller)); if (!mutualUpgrades[expectedHash]) { bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender)); mutualUpgrades[newHash] = true; emit MutualUpgradeRegistered(newHash); return; } delete mutualUpgrades[expectedHash]; // Run the rest of the upgrades _; } /* ============ Internal Functions ============ */ function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) { return msg.sender == _signerOne ? _signerTwo : _signerOne; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface IBaseManager { function setToken() external returns(ISetToken); function methodologist() external returns(address); function operator() external returns(address); function interactManager(address _module, bytes calldata _encoded) external; function transferTokens(address _token, address _destination, uint256 _amount) external; }
* METHODOLOGIST ONLY & EMERGENCY ONLY: Decrements the emergencies counter. Allows a methodologist to exit a state of emergency without replacing a protected module that was removed. This could happen if the module has no viable substitute or operator and methodologist agree that restoring normal operations is the best way forward./
function resolveEmergency() external onlyMethodologist onlyEmergency { emergencies -= 1; emit EmergencyResolved(); }
280,461
[ 1, 5277, 2311, 4842, 5511, 20747, 473, 7141, 654, 16652, 16068, 20747, 30, 31073, 1346, 326, 801, 18639, 3209, 3895, 18, 25619, 279, 707, 3966, 376, 358, 2427, 279, 919, 434, 801, 24530, 2887, 13993, 279, 4750, 1605, 716, 1703, 3723, 18, 1220, 3377, 5865, 309, 326, 1605, 711, 1158, 331, 2214, 14811, 578, 3726, 471, 707, 3966, 376, 1737, 992, 716, 3127, 6053, 2212, 5295, 353, 326, 3796, 4031, 5104, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2245, 1514, 24530, 1435, 3903, 1338, 1305, 3966, 376, 1338, 1514, 24530, 288, 203, 3639, 801, 18639, 3209, 3947, 404, 31, 203, 203, 3639, 3626, 512, 6592, 75, 2075, 12793, 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 ]
./full_match/1/0x765f64Be4D190287E8049A71D12a334Fc52b8E0a/sources/contracts/vaults/Para4626.sol
* @title Storage for Para4626 @author Spice Finance Inc/
abstract contract Para4626Storage { address public poolAddress; address public lpTokenAddress; pragma solidity ^0.8.17; }
9,793,349
[ 1, 3245, 364, 2280, 69, 8749, 5558, 225, 5878, 1812, 9458, 1359, 15090, 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, 17801, 6835, 2280, 69, 8749, 5558, 3245, 288, 203, 565, 1758, 1071, 2845, 1887, 31, 203, 203, 565, 1758, 1071, 12423, 1345, 1887, 31, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 4033, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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; } } /** * @title KYC * @dev KYC contract handles the white list for ASTCrowdsale contract * Only accounts registered in KYC contract can buy AST token. * Admins can register account, and the reason why */ contract KYC is Ownable { // check the address is registered for token sale // first boolean is true if presale else false // second boolean is true if registered else false mapping (address => mapping (bool => bool)) public registeredAddress; // check the address is admin of kyc contract mapping (address => bool) public admin; event Registered(address indexed _addr); event Unregistered(address indexed _addr); event SetAdmin(address indexed _addr); /** * @dev check whether the address is registered for token sale or not. * @param _addr address * @param _isPresale bool Whether the address is registered to presale or mainsale */ modifier onlyRegistered(address _addr, bool _isPresale) { require(registeredAddress[_addr][_isPresale]); _; } /** * @dev check whether the msg.sender is admin or not */ modifier onlyAdmin() { require(admin[msg.sender]); _; } function KYC() public { admin[msg.sender] = true; } /** * @dev set new admin as admin of KYC contract * @param _addr address The address to set as admin of KYC contract */ function setAdmin(address _addr, bool _value) public onlyOwner returns (bool) { require(_addr != address(0)); require(admin[_addr] == !_value); admin[_addr] = _value; SetAdmin(_addr); return true; } /** * @dev check the address is register * @param _addr address The address to check * @param _isPresale bool Whether the address is registered to presale or mainsale */ function isRegistered(address _addr, bool _isPresale) public view returns (bool) { return registeredAddress[_addr][_isPresale]; } /** * @dev register the address for token sale * @param _addr address The address to register for token sale * @param _isPresale bool Whether register to presale or mainsale */ function register(address _addr, bool _isPresale) public onlyAdmin { require(_addr != address(0) && registeredAddress[_addr][_isPresale] == false); registeredAddress[_addr][_isPresale] = true; Registered(_addr); } /** * @dev register the addresses for token sale * @param _addrs address[] The addresses to register for token sale * @param _isPresale bool Whether register to presale or mainsale */ function registerByList(address[] _addrs, bool _isPresale) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { register(_addrs[i], _isPresale); } } /** * @dev unregister the registered address * @param _addr address The address to unregister for token sale * @param _isPresale bool Whether unregister to presale or mainsale */ function unregister(address _addr, bool _isPresale) public onlyAdmin onlyRegistered(_addr, _isPresale) { registeredAddress[_addr][_isPresale] = false; Unregistered(_addr); } /** * @dev unregister the registered addresses * @param _addrs address[] The addresses to unregister for token sale * @param _isPresale bool Whether unregister to presale or mainsale */ function unregisterByList(address[] _addrs, bool _isPresale) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { unregister(_addrs[i], _isPresale); } } } contract PaymentFallbackReceiver { BTCPaymentI public payment; enum SaleType { pre, main } function PaymentFallbackReceiver(address _payment) public { require(_payment != address(0)); payment = BTCPaymentI(_payment); } modifier onlyPayment() { require(msg.sender == address(payment)); _; } event MintByBTC(SaleType _saleType, address indexed _beneficiary, uint256 _tokens); /** * @dev paymentFallBack() is called in BTCPayment.addPayment(). * Presale or Mainsale contract should mint token to beneficiary, * and apply corresponding ether amount to max ether cap. * @param _beneficiary ethereum address who receives tokens * @param _tokens amount of FXT to mint */ function paymentFallBack(address _beneficiary, uint256 _tokens) external onlyPayment(); } contract PresaleFallbackReceiver { bool public presaleFallBackCalled; function presaleFallBack(uint256 _presaleWeiRaised) public returns (bool); } contract BTCPaymentI is Ownable, PresaleFallbackReceiver { PaymentFallbackReceiver public presale; PaymentFallbackReceiver public mainsale; function addPayment(address _beneficiary, uint256 _tokens) public; function setPresale(address _presale) external; function setMainsale(address _mainsale) external; function presaleFallBack(uint256) public returns (bool); } contract BTCPayment is Ownable, PresaleFallbackReceiver { using SafeMath for uint256; PaymentFallbackReceiver public presale; PaymentFallbackReceiver public mainsale; event NewPayment(address _beneficiary, uint256 _tokens); function addPayment(address _beneficiary, uint256 _tokens) public onlyOwner { if (!presaleFallBackCalled) { presale.paymentFallBack(_beneficiary, _tokens); } else { mainsale.paymentFallBack(_beneficiary, _tokens); } NewPayment(_beneficiary, _tokens); } function setPresale(address _presale) external onlyOwner { require(presale == address(0)); presale = PaymentFallbackReceiver(_presale); // datatype conversion `address` to `PaymentFallbackReceiver`. not calling constructor `PaymentFallbackReceiver` } function setMainsale(address _mainsale) external onlyOwner { require(mainsale == address(0)); mainsale = PaymentFallbackReceiver(_mainsale); // datatype conversion `address` to `PaymentFallbackReceiver`. not calling constructor `PaymentFallbackReceiver` } /** * @dev Presale should notify that presale is finalized and mainsale * is going to start. */ function presaleFallBack(uint256) public returns (bool) { require(msg.sender == address(presale)); if (presaleFallBackCalled) return false; presaleFallBackCalled = true; return true; } }
* @dev unregister the registered addresses @param _addrs address[] The addresses to unregister for token sale @param _isPresale bool Whether unregister to presale or mainsale/
function unregisterByList(address[] _addrs, bool _isPresale) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { unregister(_addrs[i], _isPresale); } }
13,105,289
[ 1, 318, 4861, 326, 4104, 6138, 225, 389, 23305, 1758, 8526, 1021, 6138, 358, 10232, 364, 1147, 272, 5349, 225, 389, 291, 12236, 5349, 1426, 17403, 10232, 358, 4075, 5349, 578, 2774, 87, 5349, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 10232, 858, 682, 12, 2867, 8526, 389, 23305, 16, 1426, 389, 291, 12236, 5349, 13, 203, 565, 1071, 203, 565, 1338, 4446, 203, 225, 288, 203, 565, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 23305, 18, 2469, 31, 277, 27245, 288, 203, 1377, 10232, 24899, 23305, 63, 77, 6487, 389, 291, 12236, 5349, 1769, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xC25148cB2a1CE39d121003f26422E724bD46782C/sources/contracts/Stablecoin.sol
Calculate the fee taken on a flash loan
function flashFee(address, uint256 amount) public view override returns (uint256) { return (amount * flashFeePer10k) / 10_000; }
4,635,130
[ 1, 8695, 326, 14036, 9830, 603, 279, 9563, 28183, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9563, 14667, 12, 2867, 16, 2254, 5034, 3844, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 261, 8949, 380, 9563, 14667, 2173, 2163, 79, 13, 342, 1728, 67, 3784, 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 ]
./full_match/421613/0x53Be7B3A3C8D0240dc9ff48511d45e4f71EdDB4A/sources/src/Games/Slot.sol
@title nekopachi slot @author munji ([email protected])
contract pachiSlotV6 is Game { uint8[36] public reel; mapping(uint256 => uint256[2]) payouts; event PlaceSpin( uint256 id, address indexed user, address indexed token, uint256 amount ); event RequestPaid( uint256 _id, address _from, address tokenAddress, uint256[3][] _reels, uint256[] _payouts, uint256 _totalPayout, uint256 _totalInput ); constructor( address bankAddress, address _supraRouterAddress, uint16 _houseEdge import {Game} from "./Game.sol"; ) Game(bankAddress, _supraRouterAddress, _houseEdge) { uint8[2][8] memory symbols = [ [0, 8], [1, 7], [2, 6], [3, 5], [4, 4], [5, 3], [6, 2], [7, 1] ]; payouts[0] = [2, 25]; payouts[1] = [5, 45]; payouts[2] = [10, 100]; payouts[3] = [15, 250]; payouts[4] = [25, 550]; payouts[5] = [45, 1650]; payouts[6] = [150, 6550]; payouts[7] = [1150, 10e4]; uint8 counter = 0; for (uint8 symbol = 0; symbol < symbols.length; symbol++) { for (uint8 occur = 0; occur < symbols[symbol][1]; occur++) { reel[counter] = symbols[symbol][0]; counter++; } } } ) Game(bankAddress, _supraRouterAddress, _houseEdge) { uint8[2][8] memory symbols = [ [0, 8], [1, 7], [2, 6], [3, 5], [4, 4], [5, 3], [6, 2], [7, 1] ]; payouts[0] = [2, 25]; payouts[1] = [5, 45]; payouts[2] = [10, 100]; payouts[3] = [15, 250]; payouts[4] = [25, 550]; payouts[5] = [45, 1650]; payouts[6] = [150, 6550]; payouts[7] = [1150, 10e4]; uint8 counter = 0; for (uint8 symbol = 0; symbol < symbols.length; symbol++) { for (uint8 occur = 0; occur < symbols[symbol][1]; occur++) { reel[counter] = symbols[symbol][0]; counter++; } } } ) Game(bankAddress, _supraRouterAddress, _houseEdge) { uint8[2][8] memory symbols = [ [0, 8], [1, 7], [2, 6], [3, 5], [4, 4], [5, 3], [6, 2], [7, 1] ]; payouts[0] = [2, 25]; payouts[1] = [5, 45]; payouts[2] = [10, 100]; payouts[3] = [15, 250]; payouts[4] = [25, 550]; payouts[5] = [45, 1650]; payouts[6] = [150, 6550]; payouts[7] = [1150, 10e4]; uint8 counter = 0; for (uint8 symbol = 0; symbol < symbols.length; symbol++) { for (uint8 occur = 0; occur < symbols[symbol][1]; occur++) { reel[counter] = symbols[symbol][0]; counter++; } } } function _getPayout(uint256 betAmount) private pure returns (uint256) { } function spin( address tokenAddress, uint256 betUnit, uint8 rngCount ) external payable whenNotPaused { uint256 _totalInput = betUnit * uint256(rngCount); uint256 theorecticalMax = 10000 * uint256(rngCount); Bet memory bet = _newBet( tokenAddress, _totalInput, betUnit, rngCount ); emit PlaceSpin({ id: bet.id, user: bet.user, token: bet.token, amount: bet.amount }); } function spin( address tokenAddress, uint256 betUnit, uint8 rngCount ) external payable whenNotPaused { uint256 _totalInput = betUnit * uint256(rngCount); uint256 theorecticalMax = 10000 * uint256(rngCount); Bet memory bet = _newBet( tokenAddress, _totalInput, betUnit, rngCount ); emit PlaceSpin({ id: bet.id, user: bet.user, token: bet.token, amount: bet.amount }); } function _callback( uint256 _id, uint256[] calldata _randomNumbers ) external { require( msg.sender == address(supraRouter), "only supra router can call this function" ); Bet storage bet = bets[_id]; uint256[3][] memory _reels = new uint256[3][](_randomNumbers.length); uint256[] memory _payouts = new uint256[](_randomNumbers.length); uint256 _totalPayout = 0; for (uint8 i = 0; i < _randomNumbers.length; i++) { uint256 r1 = reel[(_randomNumbers[i] % 100) % 36]; uint256 r2 = reel[((_randomNumbers[i] % 10000) / 100) % 36]; uint256 r3 = reel[((_randomNumbers[i] % 1000000) / 10000) % 36]; uint256 payout = 0; if (r1 == r2) { uint8 pos = 0; if (r2 == r3) pos = 1; payout = (bet.betUnit * payouts[r1][pos]) / 10; } _reels[i] = [r1, r2, r3]; _payouts[i] = payout; _totalPayout += payout; } uint256 resolvedPayout = _resolveBet(bet, _totalPayout); emit RequestPaid({ _id: _id, _from: bet.user, tokenAddress: bet.token, _reels: _reels, _payouts: _payouts, _totalPayout: resolvedPayout, _totalInput: bet.amount }); } function _callback( uint256 _id, uint256[] calldata _randomNumbers ) external { require( msg.sender == address(supraRouter), "only supra router can call this function" ); Bet storage bet = bets[_id]; uint256[3][] memory _reels = new uint256[3][](_randomNumbers.length); uint256[] memory _payouts = new uint256[](_randomNumbers.length); uint256 _totalPayout = 0; for (uint8 i = 0; i < _randomNumbers.length; i++) { uint256 r1 = reel[(_randomNumbers[i] % 100) % 36]; uint256 r2 = reel[((_randomNumbers[i] % 10000) / 100) % 36]; uint256 r3 = reel[((_randomNumbers[i] % 1000000) / 10000) % 36]; uint256 payout = 0; if (r1 == r2) { uint8 pos = 0; if (r2 == r3) pos = 1; payout = (bet.betUnit * payouts[r1][pos]) / 10; } _reels[i] = [r1, r2, r3]; _payouts[i] = payout; _totalPayout += payout; } uint256 resolvedPayout = _resolveBet(bet, _totalPayout); emit RequestPaid({ _id: _id, _from: bet.user, tokenAddress: bet.token, _reels: _reels, _payouts: _payouts, _totalPayout: resolvedPayout, _totalInput: bet.amount }); } function _callback( uint256 _id, uint256[] calldata _randomNumbers ) external { require( msg.sender == address(supraRouter), "only supra router can call this function" ); Bet storage bet = bets[_id]; uint256[3][] memory _reels = new uint256[3][](_randomNumbers.length); uint256[] memory _payouts = new uint256[](_randomNumbers.length); uint256 _totalPayout = 0; for (uint8 i = 0; i < _randomNumbers.length; i++) { uint256 r1 = reel[(_randomNumbers[i] % 100) % 36]; uint256 r2 = reel[((_randomNumbers[i] % 10000) / 100) % 36]; uint256 r3 = reel[((_randomNumbers[i] % 1000000) / 10000) % 36]; uint256 payout = 0; if (r1 == r2) { uint8 pos = 0; if (r2 == r3) pos = 1; payout = (bet.betUnit * payouts[r1][pos]) / 10; } _reels[i] = [r1, r2, r3]; _payouts[i] = payout; _totalPayout += payout; } uint256 resolvedPayout = _resolveBet(bet, _totalPayout); emit RequestPaid({ _id: _id, _from: bet.user, tokenAddress: bet.token, _reels: _reels, _payouts: _payouts, _totalPayout: resolvedPayout, _totalInput: bet.amount }); } function _callback( uint256 _id, uint256[] calldata _randomNumbers ) external { require( msg.sender == address(supraRouter), "only supra router can call this function" ); Bet storage bet = bets[_id]; uint256[3][] memory _reels = new uint256[3][](_randomNumbers.length); uint256[] memory _payouts = new uint256[](_randomNumbers.length); uint256 _totalPayout = 0; for (uint8 i = 0; i < _randomNumbers.length; i++) { uint256 r1 = reel[(_randomNumbers[i] % 100) % 36]; uint256 r2 = reel[((_randomNumbers[i] % 10000) / 100) % 36]; uint256 r3 = reel[((_randomNumbers[i] % 1000000) / 10000) % 36]; uint256 payout = 0; if (r1 == r2) { uint8 pos = 0; if (r2 == r3) pos = 1; payout = (bet.betUnit * payouts[r1][pos]) / 10; } _reels[i] = [r1, r2, r3]; _payouts[i] = payout; _totalPayout += payout; } uint256 resolvedPayout = _resolveBet(bet, _totalPayout); emit RequestPaid({ _id: _id, _from: bet.user, tokenAddress: bet.token, _reels: _reels, _payouts: _payouts, _totalPayout: resolvedPayout, _totalInput: bet.amount }); } }
11,569,889
[ 1, 82, 3839, 556, 497, 77, 4694, 225, 312, 318, 21102, 261, 93, 381, 318, 78, 29, 6938, 36, 75, 4408, 18, 832, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 293, 497, 77, 8764, 58, 26, 353, 14121, 288, 203, 565, 2254, 28, 63, 5718, 65, 1071, 283, 292, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 22, 5717, 293, 2012, 87, 31, 203, 203, 565, 871, 13022, 3389, 267, 12, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 1758, 8808, 729, 16, 203, 3639, 1758, 8808, 1147, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 11272, 203, 203, 565, 871, 1567, 16507, 350, 12, 203, 3639, 2254, 5034, 389, 350, 16, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 1147, 1887, 16, 203, 3639, 2254, 5034, 63, 23, 6362, 65, 389, 266, 10558, 16, 203, 3639, 2254, 5034, 8526, 389, 84, 2012, 87, 16, 203, 3639, 2254, 5034, 389, 4963, 52, 2012, 16, 203, 3639, 2254, 5034, 389, 4963, 1210, 203, 565, 11272, 203, 203, 565, 3885, 12, 203, 3639, 1758, 11218, 1887, 16, 203, 3639, 1758, 389, 2859, 354, 8259, 1887, 16, 203, 3639, 2254, 2313, 389, 13028, 6098, 203, 203, 5666, 288, 12496, 97, 628, 25165, 12496, 18, 18281, 14432, 203, 565, 262, 14121, 12, 10546, 1887, 16, 389, 2859, 354, 8259, 1887, 16, 389, 13028, 6098, 13, 288, 203, 3639, 2254, 28, 63, 22, 6362, 28, 65, 3778, 7963, 273, 306, 203, 5411, 306, 20, 16, 1725, 6487, 203, 5411, 306, 21, 16, 2371, 6487, 203, 5411, 306, 22, 16, 1666, 6487, 203, 5411, 306, 23, 16, 1381, 6487, 203, 5411, 306, 24, 16, 1059, 6487, 203, 5411, 306, 25, 16, 890, 6487, 203, 5411, 2 ]
pragma solidity ^0.4.21; /* * Creator: CST (CryptoServices Token) */ /* * Abstract Token Smart Contract * */ /* * Safe Math Smart Contract. * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract 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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); 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); } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * CST token smart contract. */ contract CSTToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 100000000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function CSTToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "CryptoServices Token"; string constant public symbol = "CST"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
* Maximum allowed number of tokens in circulation. tokenSupply = tokensIActuallyWant (10 ^ decimals)/* Address of the owner of this smart contract./* Frozen account list holder/* Current number of tokens in circulation./* True if tokens transfers are currently frozen, false otherwise./* Create new token smart contract and make msg.sender the owner of this smart contract./
function CSTToken () { owner = msg.sender; }
13,863,571
[ 1, 13528, 2935, 1300, 434, 2430, 316, 5886, 1934, 367, 18, 1147, 3088, 1283, 273, 2430, 45, 2459, 3452, 59, 970, 225, 261, 2163, 3602, 15105, 13176, 5267, 434, 326, 3410, 434, 333, 13706, 6835, 18, 19, 478, 9808, 2236, 666, 10438, 19, 6562, 1300, 434, 2430, 316, 5886, 1934, 367, 18, 19, 1053, 309, 2430, 29375, 854, 4551, 12810, 16, 629, 3541, 18, 19, 1788, 394, 1147, 13706, 6835, 471, 1221, 1234, 18, 15330, 326, 3410, 434, 333, 13706, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 385, 882, 1345, 1832, 288, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // The functionality that all derivative contracts expose to the admin. interface AdminInterface { // Initiates the shutdown process, in case of an emergency. function emergencyShutdown() external; // A core contract method called immediately before or after any financial transaction. It pays fees and moves money // between margin accounts to make sure they reflect the NAV of the contract. function remargin() external; } contract ExpandedIERC20 is IERC20 { // Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless. function burn(uint value) external; // Mints tokens and adds them to the balance of the `to` address. // Note: this method should be permissioned to only allow designated parties to mint tokens. function mint(address to, uint value) external; } // This interface allows derivative contracts to pay Oracle fees for their use of the system. interface StoreInterface { // Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH. function payOracleFees() external payable; // Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an // ERC20 token rather than ETH. All approved tokens are transfered. function payOracleFeesErc20(address erc20Address) external; // Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the // maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the // price feed in their favor. function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount); } interface ReturnCalculatorInterface { // Computes the return between oldPrice and newPrice. function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn); // Gets the effective leverage for the return calculator. // Note: if this parameter doesn't exist for this calculator, this method should return 1. function leverage() external view returns (int _leverage); } // This interface allows contracts to query unverified prices. interface PriceFeedInterface { // Whether this PriceFeeds provides prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have // been published for this identifier. function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price); // An event fired when a price is published. event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price); } contract AddressWhitelist is Ownable { enum Status { None, In, Out } mapping(address => Status) private whitelist; address[] private whitelistIndices; // Adds an address to the whitelist function addToWhitelist(address newElement) external onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddToWhitelist(newElement); } // Removes an address from the whitelist. function removeFromWhitelist(address elementToRemove) external onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemoveFromWhitelist(elementToRemove); } } // Checks whether an address is on the whitelist. function isOnWhitelist(address elementToCheck) external view returns (bool) { return whitelist[elementToCheck] == Status.In; } // Gets all addresses that are currently included in the whitelist // Note: This method skips over, but still iterates through addresses. // It is possible for this call to run out of gas if a large number of // addresses have been removed. To prevent this unlikely scenario, we can // modify the implementation so that when addresses are removed, the last addresses // in the array is moved to the empty index. function getWhitelist() external view returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } event AddToWhitelist(address indexed addedAddress); event RemoveFromWhitelist(address indexed removedAddress); } contract Withdrawable is Ownable { // Withdraws ETH from the contract. function withdraw(uint amount) external onlyOwner { msg.sender.transfer(amount); } // Withdraws ERC20 tokens from the contract. function withdrawErc20(address erc20Address, uint amount) external onlyOwner { IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } } // This interface allows contracts to query a verified, trusted price. interface OracleInterface { // Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available. // Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if // the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this // method. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable); // Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if // the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call // this method. function getPrice(bytes32 identifier, uint time) external view returns (int price); // Returns whether the Oracle provides verified prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // An event fired when a request for a (identifier, time) pair is made. event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time); // An event fired when a verified price is available for a (identifier, time) pair. event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price); } interface RegistryInterface { struct RegisteredDerivative { address derivativeAddress; address derivativeCreator; } // Registers a new derivative. Only authorized derivative creators can call this method. function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; // Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call // this method. function addDerivativeCreator(address derivativeCreator) external; // Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this // method. function removeDerivativeCreator(address derivativeCreator) external; // Returns whether the derivative has been registered with the registry (and is therefore an authorized participant // in the UMA system). function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); // Returns a list of all derivatives that are associated with a particular party. function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives); // Returns all registered derivatives. function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives); // Returns whether an address is authorized to register new derivatives. function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized); } contract Registry is RegistryInterface, Withdrawable { using SafeMath for uint; // Array of all registeredDerivatives that are approved to use the UMA Oracle. RegisteredDerivative[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid, WasValid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; // Maps from derivative creator address to whether that derivative creator has been approved to register contracts. mapping(address => bool) private derivativeCreators; modifier onlyApprovedDerivativeCreator { require(derivativeCreators[msg.sender]); _; } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyApprovedDerivativeCreator { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender)); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit RegisterDerivative(derivativeAddress, partiesForEvent); } function addDerivativeCreator(address derivativeCreator) external onlyOwner { if (!derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = true; emit AddDerivativeCreator(derivativeCreator); } } function removeDerivativeCreator(address derivativeCreator) external onlyOwner { if (derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = false; emit RemoveDerivativeCreator(derivativeCreator); } } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { RegisteredDerivative storage derivative = registeredDerivatives[i]; if (derivativesToParties[derivative.derivativeAddress].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new RegisteredDerivative[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) { return registeredDerivatives; } function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) { return derivativeCreators[derivativeCreator]; } event RegisterDerivative(address indexed derivativeAddress, address[] parties); event AddDerivativeCreator(address indexed addedDerivativeCreator); event RemoveDerivativeCreator(address indexed removedDerivativeCreator); } contract Testable is Ownable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } modifier onlyIfTest { require(isTest); _; } function setCurrentTime(uint _time) external onlyOwner onlyIfTest { currentTime = _time; } function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract ContractCreator is Withdrawable { Registry internal registry; address internal oracleAddress; address internal storeAddress; address internal priceFeedAddress; constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress) public { registry = Registry(registryAddress); oracleAddress = _oracleAddress; storeAddress = _storeAddress; priceFeedAddress = _priceFeedAddress; } function _registerContract(address[] memory parties, address contractToRegister) internal { registry.registerDerivative(parties, contractToRegister); } } library TokenizedDerivativeParams { enum ReturnType { Linear, Compound } struct ConstructorParams { address sponsor; address admin; address oracle; address store; address priceFeed; uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying price that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of margin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18 ReturnType returnType; uint startingUnderlyingPrice; uint creationTime; } } // TokenizedDerivativeStorage: this library name is shortened due to it being used so often. library TDS { enum State { // The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as // it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state. // Possible state transitions: Disputed, Expired, Defaulted. Live, // Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in // time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn. // The resolution of these states moves the contract to the Settled state. Remargining is not allowed. // The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the // Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short // account. Otherwise, the dispute fee is added to the long margin account. // Possible state transitions: Settled. Disputed, // Contract expiration has been reached. // Possible state transitions: Settled. Expired, // The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and // move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to // Settled. // Possible state transitions: Settled. Defaulted, // UMA has manually triggered a shutdown of the account. // Possible state transitions: Settled. Emergency, // Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be // created, and contract can't remargin. // Possible state transitions: None. Settled } // The state of the token at a particular time. The state gets updated on remargin. struct TokenState { int underlyingPrice; int tokenPrice; uint time; } // The information in the following struct is only valid if in the midst of a Dispute. struct Dispute { int disputedNav; uint deposit; } struct WithdrawThrottle { uint startTime; uint remainingWithdrawal; } struct FixedParameters { // Fixed contract parameters. uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move that the long is protected against. uint disputeDeposit; // Percentage of margin requirement * 10^18 uint fixedFeePerSecond; // Percentage of nav*10^18 uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18 bytes32 product; TokenizedDerivativeParams.ReturnType returnType; uint initialTokenUnderlyingRatio; uint creationTime; string symbol; } struct ExternalAddresses { // Other addresses/contracts address sponsor; address admin; address apDelegate; OracleInterface oracle; StoreInterface store; PriceFeedInterface priceFeed; ReturnCalculatorInterface returnCalculator; IERC20 marginCurrency; } struct Storage { FixedParameters fixedParameters; ExternalAddresses externalAddresses; // Balances int shortBalance; int longBalance; State state; uint endTime; // The NAV of the contract always reflects the transition from (`prev`, `current`). // In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev` // and `latest` -> `current` (and then recompute). // In the case of a dispute, `current` might change (which is why we have to hold on to `prev`). TokenState referenceTokenState; TokenState currentTokenState; int nav; // Net asset value is measured in Wei Dispute disputeInfo; // Only populated once the contract enters a frozen state. int defaultPenaltyAmount; WithdrawThrottle withdrawThrottle; } } library TokenizedDerivativeUtils { using TokenizedDerivativeUtils for TDS.Storage; using SafeMath for uint; using SignedSafeMath for int; uint private constant SECONDS_PER_DAY = 86400; uint private constant SECONDS_PER_YEAR = 31536000; uint private constant INT_MAX = 2**255 - 1; uint private constant UINT_FP_SCALING_FACTOR = 10**18; int private constant INT_FP_SCALING_FACTOR = 10**18; modifier onlySponsor(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor); _; } modifier onlyAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrApDelegate(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); _; } // Contract initializer. Should only be called at construction. // Note: Must be a public function because structs cannot be passed as calldata (required data type for external // functions). function _initialize( TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public { s._setFixedParameters(params, symbol); s._setExternalAddresses(params); // Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally // creating rounding or overflow errors. require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9)); require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9)); // TODO(mrice32): we should have an ideal start time rather than blindly polling. (uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); // If nonzero, take the user input as the starting price. if (params.startingUnderlyingPrice != 0) { latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice); } require(latestUnderlyingPrice > 0); require(latestTime != 0); // Keep the ratio in case it's needed for margin computation. s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice)); require(s.fixedParameters.initialTokenUnderlyingRatio != 0); // Set end time to max value of uint to implement no expiry. if (params.expiry == 0) { s.endTime = ~uint(0); } else { require(params.expiry >= latestTime); s.endTime = params.expiry; } s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice); s.state = TDS.State.Live; } function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { s._remarginInternal(); int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (newTokenNav < 0) { newTokenNav = 0; } uint positiveTokenNav = _safeUintCast(newTokenNav); // Get any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). uint refund = s._pullSentMargin(marginForPurchase); // Subtract newTokenNav from amount sent. uint depositAmount = marginForPurchase.sub(positiveTokenNav); // Deposit additional margin into the short account. s._depositInternal(depositAmount); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. This should be 0 in this case, // but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure // the sender never loses money. refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav)); // Send the accumulated refund. s._sendMargin(refund); } function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external { require(s.state == TDS.State.Live || s.state == TDS.State.Settled); require(tokensToRedeem > 0); if (s.state == TDS.State.Live) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); s._remarginInternal(); require(s.state == TDS.State.Live); } ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); uint initialSupply = _totalSupply(); require(initialSupply > 0); _pullAuthorizedTokens(thisErc20Token, tokensToRedeem); thisErc20Token.burn(tokensToRedeem); emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem); // Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor // margin account. uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply); uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage); s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin)); assert(s.longBalance >= 0); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); s._sendMargin(tokenMargin); } function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) { require( s.state == TDS.State.Live, "Contract must be Live to dispute" ); uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit)); uint sendInconsistencyRefund = s._pullSentMargin(depositMargin); require(depositMargin >= requiredDeposit); uint overpaymentRefund = depositMargin.sub(requiredDeposit); s.state = TDS.State.Disputed; s.endTime = s.currentTokenState.time; s.disputeInfo.disputedNav = s.nav; s.disputeInfo.deposit = requiredDeposit; // Store the default penalty in case the dispute pushes the sponsor into default. s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav); s._requestOraclePrice(s.endTime); // Add the two types of refunds: // 1. The refund for ETH sent if it was > depositMargin. // 2. The refund for depositMargin > requiredDeposit. s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund)); } function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) { // Remargin before allowing a withdrawal, but only if in the live state. if (s.state == TDS.State.Live) { s._remarginInternal(); } // Make sure either in Live or Settled after any necessary remargin. require(s.state == TDS.State.Live || s.state == TDS.State.Settled); // If the contract has been settled or is in prefunded state then can // withdraw up to full balance. If the contract is in live state then // must leave at least the required margin. Not allowed to withdraw in // other states. int withdrawableAmount; if (s.state == TDS.State.Settled) { withdrawableAmount = s.shortBalance; } else { // Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit. uint currentTime = s.currentTokenState.time; if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) { // We've passed the previous s.withdrawThrottle window. Start new one. s.withdrawThrottle.startTime = currentTime; s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit); } int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState)); int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal); // Take the smallest of the two withdrawal limits. withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw; // Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above // ternary is more explicit. s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount); } // Can only withdraw the allowed amount. require( withdrawableAmount >= _safeIntCast(amount), "Attempting to withdraw more than allowed" ); // Transfer amount - Note: important to `-=` before the send so that the // function can not be called multiple times while waiting for transfer // to return. s.shortBalance = s.shortBalance.sub(_safeIntCast(amount)); emit Withdrawal(s.fixedParameters.symbol, amount); s._sendMargin(amount); } function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) { // Right now, only confirming prices in the defaulted state. require(s.state == TDS.State.Defaulted); // Remargin on agreed upon price. s._settleAgreedPrice(); } function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) { s.externalAddresses.apDelegate = _apDelegate; } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) { require(s.state == TDS.State.Live); s.state = TDS.State.Emergency; s.endTime = s.currentTokenState.time; s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime); s._requestOraclePrice(s.endTime); } function _settle(TDS.Storage storage s) external { s._settleInternal(); } function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { // Returns any refund due to sending more margin than the argument indicated (should only be able to happen in // the ETH case). uint refund = s._pullSentMargin(marginForPurchase); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase)); // Send the accumulated refund. s._sendMargin(refund); } function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) { // Only allow the s.externalAddresses.sponsor to deposit margin. uint refund = s._pullSentMargin(marginToDeposit); s._depositInternal(marginToDeposit); // Send any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). s._sendMargin(refund); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function _calcNAV(TDS.Storage storage s) external view returns (int navNew) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) { (TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance(); newTokenValue = newTokenState.tokenPrice; } // Returns the expected balance of the short margin account using the latest available Price Feed price. function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) { (, newShortMarginBalance) = s._calcNewTokenStateAndBalance(); } function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) { (TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance(); // If the contract is in/will be moved to a settled state, the margin requirement will be 0. int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState); return newShortMarginBalance.sub(requiredMargin); } function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) { if (s.state == TDS.State.Settled) { // No margin needs to be maintained when the contract is settled. return 0; } return s._getRequiredMargin(s.currentTokenState); } function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) { TDS.State currentState = s.state; if (currentState == TDS.State.Settled) { return false; } // Technically we should also check if price will default the contract, but that isn't a normal flow of // operations that we want to simulate: we want to discourage the sponsor remargining into a default. (uint priceFeedTime, ) = s._getLatestPrice(); if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) { return false; } return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime); } function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); return (newTokenState.underlyingPrice, newTokenState.time); } function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance) { // TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted // so the logic can be written once and used twice. However, much of this was written post-audit, so it was // deemed preferable not to modify any state changing code that could potentially introduce new security // bugs. This should be done before the next contract audit. if (s.state == TDS.State.Settled) { // If the contract is Settled, just return the current contract state. return (s.currentTokenState, s.shortBalance); } // Grab the price feed pricetime. (uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice(); bool isContractLive = s.state == TDS.State.Live; bool isContractPostExpiry = priceFeedTime >= s.endTime; // If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values. if (isContractLive && priceFeedTime <= s.currentTokenState.time) { return (s.currentTokenState, s.shortBalance); } // Determine which previous price state to use when computing the new NAV. // If the contract is live, we use the reference for the linear return type or if the contract will immediately // move to expiry. bool shouldUseReferenceTokenState = isContractLive && (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry); TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState; // Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin. (uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ? (s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) : (priceFeedTime, priceFeedPrice); // Init the returned short balance to the current short balance. newShortMarginBalance = s.shortBalance; // Subtract the oracle fees from the short balance. newShortMarginBalance = isContractLive ? newShortMarginBalance.sub( _safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) : newShortMarginBalance; // Compute the new NAV newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime); int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance)); // If the contract is frozen or will move into expiry, we need to settle it, which means adding the default // penalty and dispute deposit if necessary. if (!isContractLive || isContractPostExpiry) { // Subtract default penalty (if necessary) from the short balance. bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState); if (inDefault) { int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty(); int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ? newShortMarginBalance : expectedDefaultPenalty; newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty); } // Add the dispute deposit to the short balance if necessary. if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) { int depositValue = _safeIntCast(s.disputeInfo.deposit); newShortMarginBalance = newShortMarginBalance.add(depositValue); } } } function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice) internal returns (int navNew) { int unitNav = _safeIntCast(startingTokenPrice); s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); // Starting NAV is always 0 in the TokenizedDerivative case. navNew = 0; } function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) { s._remarginInternal(); } function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) { if(address(s.externalAddresses.marginCurrency) == erc20Address) { uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this)); int totalBalances = s.shortBalance.add(s.longBalance); assert(totalBalances >= 0); uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit); require(withdrawableAmount >= amount); } IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal { // Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that // tokens fail to conform is that they do not return a bool from certain state-changing operations. This // contract was not designed to work with those tokens because of the additional complexity they would // introduce. s.externalAddresses.marginCurrency = IERC20(params.marginCurrency); s.externalAddresses.oracle = OracleInterface(params.oracle); s.externalAddresses.store = StoreInterface(params.store); s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed); s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator); // Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product. require(s.externalAddresses.oracle.isIdentifierSupported(params.product)); require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product)); s.externalAddresses.sponsor = params.sponsor; s.externalAddresses.admin = params.admin; } function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal { // Ensure only valid enum values are provided. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.returnType == TokenizedDerivativeParams.ReturnType.Linear); // Fee must be 0 if the returnType is linear. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0); // The default penalty must be less than the required margin. require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR); s.fixedParameters.returnType = params.returnType; s.fixedParameters.defaultPenalty = params.defaultPenalty; s.fixedParameters.product = params.product; s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR); s.fixedParameters.disputeDeposit = params.disputeDeposit; s.fixedParameters.supportedMove = params.supportedMove; s.fixedParameters.withdrawLimit = params.withdrawLimit; s.fixedParameters.creationTime = params.creationTime; s.fixedParameters.symbol = symbol; } // _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for // _remargin(). function _remarginInternal(TDS.Storage storage s) internal { // If the state is not live, remargining does not make sense. require(s.state == TDS.State.Live); (uint latestTime, int latestPrice) = s._getLatestPrice(); // Checks whether contract has ended. if (latestTime <= s.currentTokenState.time) { // If the price feed hasn't advanced, remargining should be a no-op. return; } // Save the penalty using the current state in case it needs to be used. int potentialPenaltyAmount = s._computeDefaultPenalty(); if (latestTime >= s.endTime) { s.state = TDS.State.Expired; emit Expired(s.fixedParameters.symbol, s.endTime); // Applies the same update a second time to effectively move the current state to the reference state. int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time); assert(recomputedNav == s.nav); uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime); // Save the precomputed default penalty in case the expiry price pushes the sponsor into default. s.defaultPenaltyAmount = potentialPenaltyAmount; // We have no idea what the price was, exactly at s.endTime, so we can't set // s.currentTokenState, or update the nav, or do anything. s._requestOraclePrice(s.endTime); s._payOracleFees(feeAmount); return; } uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime); // Update nav of contract. int navNew = s._computeNav(latestPrice, latestTime); // Update the balances of the contract. s._updateBalances(navNew); // Make sure contract has not moved into default. bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { s.state = TDS.State.Defaulted; s.defaultPenaltyAmount = potentialPenaltyAmount; s.endTime = latestTime; // Change end time to moment when default occurred. emit Default(s.fixedParameters.symbol, latestTime, s.nav); s._requestOraclePrice(latestTime); } s._payOracleFees(feeAmount); } function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) { s._remarginInternal(); // Verify that remargining didn't push the contract into expiry or default. require(s.state == TDS.State.Live); int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (purchasedNav < 0) { purchasedNav = 0; } // Ensures that requiredNav >= navSent. refund = navSent.sub(_safeUintCast(purchasedNav)); s.longBalance = s.longBalance.add(purchasedNav); ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); thisErc20Token.mint(msg.sender, tokensToPurchase); emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); // Make sure this still satisfies the margin requirement. require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState)); } function _depositInternal(TDS.Storage storage s, uint value) internal { // Make sure that we are in a "depositable" state. require(s.state == TDS.State.Live); s.shortBalance = s.shortBalance.add(_safeIntCast(value)); emit Deposited(s.fixedParameters.symbol, value); } function _settleInternal(TDS.Storage storage s) internal { TDS.State startingState = s.state; require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired || startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency); s._settleVerifiedPrice(); if (startingState == TDS.State.Disputed) { int depositValue = _safeIntCast(s.disputeInfo.deposit); if (s.nav != s.disputeInfo.disputedNav) { s.shortBalance = s.shortBalance.add(depositValue); } else { s.longBalance = s.longBalance.add(depositValue); } } } // Deducts the fees from the margin account. function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) { feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime); s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount)); // If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the // contract. } // Pays out the fees to the Oracle. function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal { if (feeAmount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { s.externalAddresses.store.payOracleFees.value(feeAmount)(); } else { require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount)); s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency)); } } function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal view returns (uint feeAmount) { // The profit from corruption is set as the max(longBalance, shortBalance). int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance; uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc)); // Ensure the fee returned can actually be paid by the short margin account. uint shortBalance = _safeUintCast(s.shortBalance); return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount; } function _computeNewTokenState(TDS.Storage storage s, TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime) internal view returns (TDS.TokenState memory newTokenState) { int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn( beginningTokenState.underlyingPrice, latestUnderlyingPrice); int tokenReturn = underlyingReturn.sub( _safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time)))); int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR); // In the compound case, don't allow the token price to go below 0. if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) { tokenMultiplier = 0; } int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier); newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime); } function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState) internal view returns (bool doesSatisfyRequirement) { return s._getRequiredMargin(tokenState) <= balance; } function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal { uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime); if (expectedTime == 0) { // The Oracle price is already available, settle the contract right away. s._settleInternal(); } } function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) { (latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); require(latestTime != 0); } function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) { navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime); } else { assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear); navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime); } } function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { s.referenceTokenState = s.currentTokenState; s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { // Only update the time - don't update the prices becuase all price changes are relative to the initial price. s.referenceTokenState.time = s.currentTokenState.time; s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) { // We're updating `last` based on what the Oracle has told us. assert(s.endTime == recomputeTime); s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } // Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all // of the settlement logic including assessing penalties and then moves the state to `Settled`. function _settleWithPrice(TDS.Storage storage s, int price) internal { // Remargin at whatever price we're using (verified or unverified). s._updateBalances(s._recomputeNav(price, s.endTime)); bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { int expectedDefaultPenalty = s._getDefaultPenalty(); int penalty = (s.shortBalance < expectedDefaultPenalty) ? s.shortBalance : expectedDefaultPenalty; s.shortBalance = s.shortBalance.sub(penalty); s.longBalance = s.longBalance.add(penalty); } s.state = TDS.State.Settled; emit Settled(s.fixedParameters.symbol, s.endTime, s.nav); } function _updateBalances(TDS.Storage storage s, int navNew) internal { // Compute difference -- Add the difference to owner and subtract // from counterparty. Then update nav state variable. int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance); s.nav = navNew; s.longBalance = s.longBalance.add(longDiff); s.shortBalance = s.shortBalance.sub(longDiff); } function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return s.defaultPenaltyAmount; } function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty); } function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState) internal view returns (int requiredMargin) { int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage()); int effectiveNotional; if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) { int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude); effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR); } else { int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply()); effectiveNotional = currentNav.mul(leverageMagnitude); } // Take the absolute value of the notional since a negative notional has similar risk properties to a positive // notional of the same size, and, therefore, requires the same margin. requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove); } function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) { if (address(s.externalAddresses.marginCurrency) == address(0x0)) { // Refund is any amount of ETH that was sent that was above the amount that was expected. // Note: SafeMath will force a revert if msg.value < expectedMargin. return msg.value.sub(expectedMargin); } else { // If we expect an ERC20 token, no ETH should be sent. require(msg.value == 0); _pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin); // There is never a refund in the ERC20 case since we use the argument to determine how much to "pull". return 0; } } function _sendMargin(TDS.Storage storage s, uint amount) internal { // There's no point in attempting a send if there's nothing to send. if (amount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { msg.sender.transfer(amount); } else { require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount)); } } function _settleAgreedPrice(TDS.Storage storage s) internal { int agreedPrice = s.currentTokenState.underlyingPrice; s._settleWithPrice(agreedPrice); } function _settleVerifiedPrice(TDS.Storage storage s) internal { int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime); s._settleWithPrice(oraclePrice); } function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private { // If nothing is being pulled, there's no point in calling a transfer. if (amountToPull > 0) { require(erc20.transferFrom(msg.sender, address(this), amountToPull)); } } // Gets the change in balance for the long side. // Note: there's a function for this because signage is tricky here, and it must be done the same everywhere. function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) { int newLongBalance = navNew; // Long balance cannot go below zero. if (newLongBalance < 0) { newLongBalance = 0; } longDiff = newLongBalance.sub(longBalance); // Cannot pull more margin from the short than is available. if (longDiff > shortBalance) { longDiff = shortBalance; } } function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) { int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice); navNew = navPreDivision.div(INT_FP_SCALING_FACTOR); // The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens // cannot be purchased or backed with less than their true value. if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) { navNew = navNew.add(1); } } function _totalSupply() private view returns (uint totalSupply) { ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); return thisErc20Token.totalSupply(); } function _takePercentage(uint value, uint percentage) private pure returns (uint result) { return value.mul(percentage).div(UINT_FP_SCALING_FACTOR); } function _takePercentage(int value, uint percentage) private pure returns (int result) { return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR); } function _takePercentage(int value, int percentage) private pure returns (int result) { return value.mul(percentage).div(INT_FP_SCALING_FACTOR); } function _absoluteValue(int value) private pure returns (int result) { return value < 0 ? value.mul(-1) : value; } function _safeIntCast(uint value) private pure returns (int result) { require(value <= INT_MAX); return int(value); } function _safeUintCast(int value) private pure returns (uint result) { require(value >= 0); return uint(value); } // Note that we can't have the symbol parameter be `indexed` due to: // TypeError: Indexed reference types cannot yet be used with ABIEncoderV2. // An event emitted when the NAV of the contract changes. event NavUpdated(string symbol, int newNav, int newTokenPrice); // An event emitted when the contract enters the Default state on a remargin. event Default(string symbol, uint defaultTime, int defaultNav); // An event emitted when the contract settles. event Settled(string symbol, uint settleTime, int finalNav); // An event emitted when the contract expires. event Expired(string symbol, uint expiryTime); // An event emitted when the contract's NAV is disputed by the sponsor. event Disputed(string symbol, uint timeDisputed, int navDisputed); // An event emitted when the contract enters emergency shutdown. event EmergencyShutdownTransition(string symbol, uint shutdownTime); // An event emitted when tokens are created. event TokensCreated(string symbol, uint numTokensCreated); // An event emitted when tokens are redeemed. event TokensRedeemed(string symbol, uint numTokensRedeemed); // An event emitted when margin currency is deposited. event Deposited(string symbol, uint amount); // An event emitted when margin currency is withdrawn. event Withdrawal(string symbol, uint amount); } // TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality. contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 { using TokenizedDerivativeUtils for TDS.Storage; // Note: these variables are to give ERC20 consumers information about the token. string public name; string public symbol; uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase TDS.Storage public derivativeStorage; constructor( TokenizedDerivativeParams.ConstructorParams memory params, string memory _name, string memory _symbol ) public { // Set token properties. name = _name; symbol = _symbol; // Initialize the contract. derivativeStorage._initialize(params, _symbol); } // Creates tokens with sent margin and returns additional margin. function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._createTokens(marginForPurchase, tokensToPurchase); } // Creates tokens with sent margin and deposits additional margin in short account. function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase); } // Redeems tokens for margin currency. function redeemTokens(uint tokensToRedeem) external { derivativeStorage._redeemTokens(tokensToRedeem); } // Triggers a price dispute for the most recent remargin time. function dispute(uint depositMargin) external payable { derivativeStorage._dispute(depositMargin); } // Withdraws `amount` from short margin account. function withdraw(uint amount) external { derivativeStorage._withdraw(amount); } // Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and // short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements. function remargin() external { derivativeStorage._remargin(); } // Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on // contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long // account. function acceptPriceAndSettle() external { derivativeStorage._acceptPriceAndSettle(); } // Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no // Delegate AP. function setApDelegate(address apDelegate) external { derivativeStorage._setApDelegate(apDelegate); } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function emergencyShutdown() external { derivativeStorage._emergencyShutdown(); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function calcNAV() external view returns (int navNew) { return derivativeStorage._calcNAV(); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function calcTokenValue() external view returns (int newTokenValue) { return derivativeStorage._calcTokenValue(); } // Returns the expected balance of the short margin account using the latest available Price Feed price. function calcShortMarginBalance() external view returns (int newShortMarginBalance) { return derivativeStorage._calcShortMarginBalance(); } // Returns the expected short margin in excess of the margin requirement using the latest available Price Feed // price. Value will be negative if the short margin is expected to be below the margin requirement. function calcExcessMargin() external view returns (int excessMargin) { return derivativeStorage._calcExcessMargin(); } // Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the // latest available Price Feed price. function getCurrentRequiredMargin() external view returns (int requiredMargin) { return derivativeStorage._getCurrentRequiredMargin(); } // Returns whether the contract can be settled, i.e., is it valid to call settle() now. function canBeSettled() external view returns (bool canContractBeSettled) { return derivativeStorage._canBeSettled(); } // Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if // the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled. // Reverts if no Oracle price is available but an Oracle price is required. function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) { return derivativeStorage._getUpdatedUnderlyingPrice(); } // When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract // into the `Settled` state. function settle() external { derivativeStorage._settle(); } // Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call) // to the short account. function deposit(uint amountToDeposit) external payable { derivativeStorage._deposit(amountToDeposit); } // Allows the sponsor to withdraw any ERC20 balance that is not the margin token. function withdrawUnexpectedErc20(address erc20Address, uint amount) external { derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount); } // ExpandedIERC20 methods. modifier onlyThis { require(msg.sender == address(this)); _; } // Only allow calls from this contract or its libraries to burn tokens. function burn(uint value) external onlyThis { // Only allow calls from this contract or its libraries to burn tokens. _burn(msg.sender, value); } // Only allow calls from this contract or its libraries to mint tokens. function mint(address to, uint256 value) external onlyThis { _mint(to, value); } // These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events // here as well. event NavUpdated(string symbol, int newNav, int newTokenPrice); event Default(string symbol, uint defaultTime, int defaultNav); event Settled(string symbol, uint settleTime, int finalNav); event Expired(string symbol, uint expiryTime); event Disputed(string symbol, uint timeDisputed, int navDisputed); event EmergencyShutdownTransition(string symbol, uint shutdownTime); event TokensCreated(string symbol, uint numTokensCreated); event TokensRedeemed(string symbol, uint numTokensRedeemed); event Deposited(string symbol, uint amount); event Withdrawal(string symbol, uint amount); } contract TokenizedDerivativeCreator is ContractCreator, Testable { struct Params { uint defaultPenalty; // Percentage of mergin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of mergin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of shortBalance * 10^18 TokenizedDerivativeParams.ReturnType returnType; uint startingUnderlyingPrice; string name; string symbol; } AddressWhitelist public sponsorWhitelist; AddressWhitelist public returnCalculatorWhitelist; AddressWhitelist public marginCurrencyWhitelist; constructor( address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress, address _sponsorWhitelist, address _returnCalculatorWhitelist, address _marginCurrencyWhitelist, bool _isTest ) public ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress) Testable(_isTest) { sponsorWhitelist = AddressWhitelist(_sponsorWhitelist); returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist); marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist); } function createTokenizedDerivative(Params memory params) public returns (address derivativeAddress) { TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol); address[] memory parties = new address[](1); parties[0] = msg.sender; _registerContract(parties, address(derivative)); return address(derivative); } // Converts createTokenizedDerivative params to TokenizedDerivative constructor params. function _convertParams(Params memory params) private view returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams) { // Copy and verify externally provided variables. require(sponsorWhitelist.isOnWhitelist(msg.sender)); constructorParams.sponsor = msg.sender; require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator)); constructorParams.returnCalculator = params.returnCalculator; require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency)); constructorParams.marginCurrency = params.marginCurrency; constructorParams.defaultPenalty = params.defaultPenalty; constructorParams.supportedMove = params.supportedMove; constructorParams.product = params.product; constructorParams.fixedYearlyFee = params.fixedYearlyFee; constructorParams.disputeDeposit = params.disputeDeposit; constructorParams.startingTokenPrice = params.startingTokenPrice; constructorParams.expiry = params.expiry; constructorParams.withdrawLimit = params.withdrawLimit; constructorParams.returnType = params.returnType; constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice; // Copy internal variables. constructorParams.priceFeed = priceFeedAddress; constructorParams.oracle = oracleAddress; constructorParams.store = storeAddress; constructorParams.admin = oracleAddress; constructorParams.creationTime = getCurrentTime(); } }
Deposit additional margin into the short account.
s._depositInternal(depositAmount);
972,293
[ 1, 758, 1724, 3312, 7333, 1368, 326, 3025, 2236, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 272, 6315, 323, 1724, 3061, 12, 323, 1724, 6275, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.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 !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "./interfaces/IController.sol"; import "./interfaces/IStrategy.sol"; import "./interfaces/IConverter.sol"; /// @title Controller /// @notice The contract is the middleman between vault and strategy, it balances and trigger earn processes contract Controller is IController, Ownable, Initializable { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Emits when funds are withdrawn fully from related to vault strategy /// @param _token Token address to be withdrawn event WithdrawToVaultAll(address _token); event Earn(address _token, uint256 _amount); /// @dev token => vault mapping(address => address) public override vaults; /// @dev token => strategy mapping(address => address) public override strategies; /// @dev from => to => converter address mapping(address => mapping(address => address)) public override converters; /// @dev token => strategy => is strategy approved mapping(address => mapping(address => bool)) public override approvedStrategies; /// @notice Strategist is an actor who created the strategies and he is receiving fees from strategies execution address public strategist; /// @notice Treasury contract address (used to channel fees to governance and rewards for voting process and investors) address private _treasury; /// @dev Prevents other msg.sender than either governance or strategist addresses modifier onlyOwnerOrStrategist() { require( _msgSender() == strategist || _msgSender() == owner(), "!governance|strategist" ); _; } /// @notice Default initialize method for solving migration linearization problem /// @dev Called once only by deployer /// @param _initialTreasury treasury contract address /// @param _initialStrategist strategist address function configure( address _initialTreasury, address _initialStrategist, address _governance ) external onlyOwner initializer { _treasury = _initialTreasury; strategist = _initialStrategist; transferOwnership(_governance); } /// @notice Used only to rescue stuck funds from controller to msg.sender /// @param _token Token to rescue /// @param _amount Amount tokens to rescue function inCaseTokensGetStuck(address _token, uint256 _amount) external onlyOwner { IERC20(_token).transfer(_msgSender(), _amount); } /// @notice Used only to rescue stuck or unrelated funds from strategy to vault /// @param _strategy Strategy address /// @param _token Unrelated token address function inCaseStrategyTokenGetStuck(address _strategy, address _token) external onlyOwnerOrStrategist { IStrategy(_strategy).withdraw(_token); } /// @notice Withdraws funds from strategy to related vault /// @param _token Token address to withdraw /// @param _amount Amount tokens function withdraw(address _token, uint256 _amount) external override { IStrategy(strategies[_token]).withdraw(_amount); } function claim(address _wantToken, address _tokenToClaim) external override { IStrategy(strategies[_wantToken]).claim(_tokenToClaim); } /// @notice forces the strategy to take away the rewards due to it // this method must call via backend /// @param _token want token address function getRewardStrategy(address _token) external override { IStrategy(strategies[_token]).getRewards(); } /// @notice Usual setter with additional checks /// @param _newTreasury New value function setTreasury(address _newTreasury) external onlyOwner { require(_treasury != _newTreasury, "!old"); require(_newTreasury != address(0), "!treasury"); require(_newTreasury.isContract(), "!contract"); _treasury = _newTreasury; } /// @notice Usual setter with check if param is new /// @param _newStrategist New value function setStrategist(address _newStrategist) external onlyOwner { require(strategist != _newStrategist, "!old"); strategist = _newStrategist; } /// @notice Used to obtain fees receivers address /// @return Treasury contract address function rewards() external view override returns (address) { return _treasury; } /// @notice Usual setter of vault in mapping with check if new vault is not address(0) /// @param _token Business logic token of the vault /// @param _vault Vault address function setVault(address _token, address _vault) external override onlyOwnerOrStrategist { require(vaults[_token] == address(0), "!vault 0"); vaults[_token] = _vault; } /// @notice Usual setter of converter contract, it implements the optimal logic to token conversion /// @param _input Input token address /// @param _output Output token address /// @param _converter Converter contract function setConverter( address _input, address _output, address _converter ) external onlyOwnerOrStrategist { converters[_input][_output] = _converter; } /// @notice Sets new link between business logic token and strategy, and if strategy is already used, withdraws all funds from it to the vault /// @param _token Business logic token address /// @param _strategy Corresponded strategy contract address function setStrategy(address _token, address _strategy) external override onlyOwnerOrStrategist { require(approvedStrategies[_token][_strategy], "!approved"); address _current = strategies[_token]; if (_current != address(0)) { uint256 amount = IERC20(IStrategy(_current).want()).balanceOf( address(this) ); IStrategy(_current).withdraw(amount); emit WithdrawToVaultAll(_token); } strategies[_token] = _strategy; } /// @notice Approves strategy to be added to mapping, needs to be done before setting strategy /// @param _token Business logic token address /// @param _strategy Strategy contract address /// @param _status Approved or not (bool)? function setApprovedStrategy( address _token, address _strategy, bool _status ) external onlyOwner { approvedStrategies[_token][_strategy] = _status; } /// @notice The method converts if needed given token to business logic strategy token, /// transfers converted tokens to strategy, and executes the business logic /// @param _token Given token address (wERC20) /// @param _amount Amount of given token address function earn(address _token, uint256 _amount) public override { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; require(converter != address(0), "!converter"); require( IERC20(_token).transfer(converter, _amount), "!transferConverterToken" ); _amount = IConverter(converter).convert(_strategy); } require( IERC20(_want).transfer(_strategy, _amount), "!transferStrategyWant" ); IStrategy(_strategy).deposit(); emit Earn(_token, _amount); } } pragma solidity ^0.6.0; interface IController { function withdraw(address, uint256) external; function earn(address, uint256) external; function rewards() external view returns (address); function vaults(address) external view returns (address); function strategies(address) external view returns (address); function approvedStrategies(address, address) external view returns (bool); function setVault(address, address) external; function setStrategy(address, address) external; function converters(address, address) external view returns (address); function claim(address, address) external; function getRewardStrategy(address _strategy) external; } pragma solidity ^0.6.0; interface IConverter { function convert(address) external returns (uint256); } pragma solidity ^0.6.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 withdraw(address) external; /// Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; function balanceOf() external view returns (uint256); function setController(address) external; function setWant(address) external; function getRewards() external; function claim(address) external returns (bool); }
@notice Approves strategy to be added to mapping, needs to be done before setting strategy @param _token Business logic token address @param _strategy Strategy contract address @param _status Approved or not (bool)?
function setApprovedStrategy( address _token, address _strategy, bool _status ) external onlyOwner { approvedStrategies[_token][_strategy] = _status; }
11,851,363
[ 1, 12053, 3324, 6252, 358, 506, 3096, 358, 2874, 16, 4260, 358, 506, 2731, 1865, 3637, 6252, 225, 389, 2316, 21759, 4058, 1147, 1758, 225, 389, 14914, 19736, 6835, 1758, 225, 389, 2327, 1716, 685, 2155, 578, 486, 261, 6430, 9945, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 31639, 4525, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 1758, 389, 14914, 16, 203, 3639, 1426, 389, 2327, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 20412, 1585, 15127, 63, 67, 2316, 6362, 67, 14914, 65, 273, 389, 2327, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // Some parts: Apache-2.0 // ==== sha3_c.c BEGIN ===================================================================================================================== //////////////////////////////////////// // A) The following code was imported from "fips202.c" // Based on the public domain implementation in // crypto_hash/keccakc512/simple/ from http://bench.cr.yp.to/supercop.html // by Ronny Van Keer // and the public domain "TweetFips202" implementation // from https://twitter.com/tweetfips202 // by Gilles Van Assche, Daniel J. Bernstein, and Peter Schwabe // License: Public domain // // B) SHAKE256_RATE constant from... // file: sha3_c.c // brief: Implementation of the OQS SHA3 API via the files fips202.c // from: PQClean (https://github.com/PQClean/PQClean/tree/master/common) // License: MIT //////////////////////////////////////// contract falcon512_signature_verify { uint32 constant SHAKE256_RATE = 136; // The SHAKE-256 byte absorption rate (aka OQS_SHA3_SHAKE256_RATE) /////////////////////////////////////// // Constants /////////////////////////////////////// int16 constant private CTX_ELEMENTS = 26; // Number of uint64 context elements int16 constant private PQC_SHAKEINCCTX_BYTES = (8 * CTX_ELEMENTS); // (sizeof(uint64) * 26) int16 constant private NROUNDS = 24; /////////////////////////////////////// // Variables /////////////////////////////////////// // Space to hold the state of the SHAKE-256 incremental hashing API. // uint64[26]: Input/Output incremental state // * First 25 values represent Keccak state. // * 26th value represents either the number of absorbed bytes // that have not been permuted, or not-yet-squeezed bytes. //byte[PQC_SHAKEINCCTX_BYTES] constant private shake256_context; // Internal state. uint64[CTX_ELEMENTS] private shake256_context64; // Internal state. // Keccak round constants uint64[NROUNDS] private KeccakF_RoundConstants = [ 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008 ]; /////////////////////////////////////// // Implementation: Keccak /////////////////////////////////////// //////////////////////////////////////// // Solidity implementation of the macro... // #define ROL(a, offset) (((a) << (offset)) ^ ((a) >> (64 - (offset)))) //////////////////////////////////////// function ROL(uint64 a, uint16 offset) private pure returns (uint64) { return (((a) << (offset)) ^ ((a) >> (64 - (offset)))); } /////////////////////////////////////// // /////////////////////////////////////// function byte_array_uint16_get(bytes memory bytearray, uint32 wordindex) private pure returns (uint16 result16) { // If the array was an array of uint16 values: // result16 = wordarray[wordindex]; // TODO: Check me, incl endianess result16 = uint16((uint8(bytearray[wordindex*2]) << 8) | uint8(bytearray[wordindex*2+1])); } /////////////////////////////////////// // /////////////////////////////////////// function byte_array_uint16_set(bytes memory bytearray, uint32 wordindex, uint16 value16) private pure { // If the array was an array of uint16 values: // wordarray[wordindex] = value16; // TODO: Check me, incl endianess bytearray[wordindex*2 ] = bytes1(uint8(uint16(value16) >> 8 )); bytearray[wordindex*2+1] = bytes1(uint8(uint16(value16) & 0x00FF)); } /////////////////////////////////////// // /////////////////////////////////////// function byte_array_int16_set(bytes memory bytearray, uint32 wordindex, int16 value16) private pure { // If the array was an array of uint16 values: // wordarray[wordindex] = value16; // TODO: Check me, incl endianess and sign bytearray[wordindex*2 ] = bytes1(uint8(int16(value16) >> 8 )); bytearray[wordindex*2+1] = bytes1(uint8(int16(value16) & 0x00FF)); } // Moved from local vars in KeccakF1600_StatePermute() to here in order to avoid stack overflow uint64 Aba; uint64 Abe; uint64 Abi; uint64 Abo; uint64 Abu; uint64 Aga; uint64 Age; uint64 Agi; uint64 Ago; uint64 Agu; uint64 Aka; uint64 Ake; uint64 Aki; uint64 Ako; uint64 Aku; uint64 Ama; uint64 Ame; uint64 Ami; uint64 Amo; uint64 Amu; uint64 Asa; uint64 Ase; uint64 Asi; uint64 Aso; uint64 Asu; uint64 BCa; uint64 BCe; uint64 BCi; uint64 BCo; uint64 BCu; uint64 Da ; uint64 De ; uint64 Di ; uint64 Do ; uint64 Du ; uint64 Eba; uint64 Ebe; uint64 Ebi; uint64 Ebo; uint64 Ebu; uint64 Ega; uint64 Ege; uint64 Egi; uint64 Ego; uint64 Egu; uint64 Eka; uint64 Eke; uint64 Eki; uint64 Eko; uint64 Eku; uint64 Ema; uint64 Eme; uint64 Emi; uint64 Emo; uint64 Emu; uint64 Esa; uint64 Ese; uint64 Esi; uint64 Eso; uint64 Esu; //////////////////////////////////////// // KeccakF1600_StatePermute() // Input parameters supplied in member variable shake256_context64. // Output values are written to the same member variable. //////////////////////////////////////// function KeccakF1600_StatePermute() public payable { //fprintf(stdout, "TRACE: KeccakF1600_StatePermute()\n"); int round; // copyFromState(A, state) Aba = shake256_context64[ 0]; Abe = shake256_context64[ 1]; Abi = shake256_context64[ 2]; Abo = shake256_context64[ 3]; Abu = shake256_context64[ 4]; Aga = shake256_context64[ 5]; Age = shake256_context64[ 6]; Agi = shake256_context64[ 7]; Ago = shake256_context64[ 8]; Agu = shake256_context64[ 9]; Aka = shake256_context64[10]; Ake = shake256_context64[11]; Aki = shake256_context64[12]; Ako = shake256_context64[13]; Aku = shake256_context64[14]; Ama = shake256_context64[15]; Ame = shake256_context64[16]; Ami = shake256_context64[17]; Amo = shake256_context64[18]; Amu = shake256_context64[19]; Asa = shake256_context64[20]; Ase = shake256_context64[21]; Asi = shake256_context64[22]; Aso = shake256_context64[23]; Asu = shake256_context64[24]; for (round = 0; round < NROUNDS; round += 2) { // prepareTheta BCa = Aba ^ Aga ^ Aka ^ Ama ^ Asa; BCe = Abe ^ Age ^ Ake ^ Ame ^ Ase; BCi = Abi ^ Agi ^ Aki ^ Ami ^ Asi; BCo = Abo ^ Ago ^ Ako ^ Amo ^ Aso; BCu = Abu ^ Agu ^ Aku ^ Amu ^ Asu; // thetaRhoPiChiIotaPrepareTheta(round , A, E) Da = BCu ^ ROL(BCe, 1); De = BCa ^ ROL(BCi, 1); Di = BCe ^ ROL(BCo, 1); Do = BCi ^ ROL(BCu, 1); Du = BCo ^ ROL(BCa, 1); Aba ^= Da; BCa = Aba; Age ^= De; BCe = ROL(Age, 44); Aki ^= Di; BCi = ROL(Aki, 43); Amo ^= Do; BCo = ROL(Amo, 21); Asu ^= Du; BCu = ROL(Asu, 14); Eba = BCa ^ ((~BCe) & BCi); Eba ^= KeccakF_RoundConstants[uint256(round)]; Ebe = BCe ^ ((~BCi) & BCo); Ebi = BCi ^ ((~BCo) & BCu); Ebo = BCo ^ ((~BCu) & BCa); Ebu = BCu ^ ((~BCa) & BCe); Abo ^= Do; BCa = ROL(Abo, 28); Agu ^= Du; BCe = ROL(Agu, 20); Aka ^= Da; BCi = ROL(Aka, 3); Ame ^= De; BCo = ROL(Ame, 45); Asi ^= Di; BCu = ROL(Asi, 61); Ega = BCa ^ ((~BCe) & BCi); Ege = BCe ^ ((~BCi) & BCo); Egi = BCi ^ ((~BCo) & BCu); Ego = BCo ^ ((~BCu) & BCa); Egu = BCu ^ ((~BCa) & BCe); Abe ^= De; BCa = ROL(Abe, 1); Agi ^= Di; BCe = ROL(Agi, 6); Ako ^= Do; BCi = ROL(Ako, 25); Amu ^= Du; BCo = ROL(Amu, 8); Asa ^= Da; BCu = ROL(Asa, 18); Eka = BCa ^ ((~BCe) & BCi); Eke = BCe ^ ((~BCi) & BCo); Eki = BCi ^ ((~BCo) & BCu); Eko = BCo ^ ((~BCu) & BCa); Eku = BCu ^ ((~BCa) & BCe); Abu ^= Du; BCa = ROL(Abu, 27); Aga ^= Da; BCe = ROL(Aga, 36); Ake ^= De; BCi = ROL(Ake, 10); Ami ^= Di; BCo = ROL(Ami, 15); Aso ^= Do; BCu = ROL(Aso, 56); Ema = BCa ^ ((~BCe) & BCi); Eme = BCe ^ ((~BCi) & BCo); Emi = BCi ^ ((~BCo) & BCu); Emo = BCo ^ ((~BCu) & BCa); Emu = BCu ^ ((~BCa) & BCe); Abi ^= Di; BCa = ROL(Abi, 62); Ago ^= Do; BCe = ROL(Ago, 55); Aku ^= Du; BCi = ROL(Aku, 39); Ama ^= Da; BCo = ROL(Ama, 41); Ase ^= De; BCu = ROL(Ase, 2); Esa = BCa ^ ((~BCe) & BCi); Ese = BCe ^ ((~BCi) & BCo); Esi = BCi ^ ((~BCo) & BCu); Eso = BCo ^ ((~BCu) & BCa); Esu = BCu ^ ((~BCa) & BCe); // prepareTheta BCa = Eba ^ Ega ^ Eka ^ Ema ^ Esa; BCe = Ebe ^ Ege ^ Eke ^ Eme ^ Ese; BCi = Ebi ^ Egi ^ Eki ^ Emi ^ Esi; BCo = Ebo ^ Ego ^ Eko ^ Emo ^ Eso; BCu = Ebu ^ Egu ^ Eku ^ Emu ^ Esu; // thetaRhoPiChiIotaPrepareTheta(round+1, E, A) Da = BCu ^ ROL(BCe, 1); De = BCa ^ ROL(BCi, 1); Di = BCe ^ ROL(BCo, 1); Do = BCi ^ ROL(BCu, 1); Du = BCo ^ ROL(BCa, 1); Eba ^= Da; BCa = Eba; Ege ^= De; BCe = ROL(Ege, 44); Eki ^= Di; BCi = ROL(Eki, 43); Emo ^= Do; BCo = ROL(Emo, 21); Esu ^= Du; BCu = ROL(Esu, 14); Aba = BCa ^ ((~BCe) & BCi); Aba ^= KeccakF_RoundConstants[uint256(round + 1)]; Abe = BCe ^ ((~BCi) & BCo); Abi = BCi ^ ((~BCo) & BCu); Abo = BCo ^ ((~BCu) & BCa); Abu = BCu ^ ((~BCa) & BCe); Ebo ^= Do; BCa = ROL(Ebo, 28); Egu ^= Du; BCe = ROL(Egu, 20); Eka ^= Da; BCi = ROL(Eka, 3); Eme ^= De; BCo = ROL(Eme, 45); Esi ^= Di; BCu = ROL(Esi, 61); Aga = BCa ^ ((~BCe) & BCi); Age = BCe ^ ((~BCi) & BCo); Agi = BCi ^ ((~BCo) & BCu); Ago = BCo ^ ((~BCu) & BCa); Agu = BCu ^ ((~BCa) & BCe); Ebe ^= De; BCa = ROL(Ebe, 1); Egi ^= Di; BCe = ROL(Egi, 6); Eko ^= Do; BCi = ROL(Eko, 25); Emu ^= Du; BCo = ROL(Emu, 8); Esa ^= Da; BCu = ROL(Esa, 18); Aka = BCa ^ ((~BCe) & BCi); Ake = BCe ^ ((~BCi) & BCo); Aki = BCi ^ ((~BCo) & BCu); Ako = BCo ^ ((~BCu) & BCa); Aku = BCu ^ ((~BCa) & BCe); Ebu ^= Du; BCa = ROL(Ebu, 27); Ega ^= Da; BCe = ROL(Ega, 36); Eke ^= De; BCi = ROL(Eke, 10); Emi ^= Di; BCo = ROL(Emi, 15); Eso ^= Do; BCu = ROL(Eso, 56); Ama = BCa ^ ((~BCe) & BCi); Ame = BCe ^ ((~BCi) & BCo); Ami = BCi ^ ((~BCo) & BCu); Amo = BCo ^ ((~BCu) & BCa); Amu = BCu ^ ((~BCa) & BCe); Ebi ^= Di; BCa = ROL(Ebi, 62); Ego ^= Do; BCe = ROL(Ego, 55); Eku ^= Du; BCi = ROL(Eku, 39); Ema ^= Da; BCo = ROL(Ema, 41); Ese ^= De; BCu = ROL(Ese, 2); Asa = BCa ^ ((~BCe) & BCi); Ase = BCe ^ ((~BCi) & BCo); Asi = BCi ^ ((~BCo) & BCu); Aso = BCo ^ ((~BCu) & BCa); Asu = BCu ^ ((~BCa) & BCe); } // copyToState(state, A) shake256_context64[ 0] = Aba; shake256_context64[ 1] = Abe; shake256_context64[ 2] = Abi; shake256_context64[ 3] = Abo; shake256_context64[ 4] = Abu; shake256_context64[ 5] = Aga; shake256_context64[ 6] = Age; shake256_context64[ 7] = Agi; shake256_context64[ 8] = Ago; shake256_context64[ 9] = Agu; shake256_context64[10] = Aka; shake256_context64[11] = Ake; shake256_context64[12] = Aki; shake256_context64[13] = Ako; shake256_context64[14] = Aku; shake256_context64[15] = Ama; shake256_context64[16] = Ame; shake256_context64[17] = Ami; shake256_context64[18] = Amo; shake256_context64[19] = Amu; shake256_context64[20] = Asa; shake256_context64[21] = Ase; shake256_context64[22] = Asi; shake256_context64[23] = Aso; shake256_context64[24] = Asu; } //////////////////////////////////////// // //////////////////////////////////////// function keccak_inc_init() public payable { uint32 i; //fprintf(stdout, "TRACE: keccak_inc_init()\n"); for (i = 0; i < 25; ++i) { shake256_context64[i] = 0; } shake256_context64[25] = 0; } //////////////////////////////////////// // //////////////////////////////////////// function keccak_inc_absorb(uint32 r, bytes memory m, uint32 mlen) public pure { uint32 i; //fprintf(stdout, "TRACE: keccak_inc_absorb()\n"); while (mlen + shake256_context64[25] >= r) { for (i = 0; i < r - uint32(shake256_context64[25]); i++) { /////////////////////////////////////////////////////////////////////////// //uint64 x = shake256_context64[(shake256_context64[25] + i) >> 3]; //uint64 y5 = shake256_context64[25] + i; //uint64 y6 = y5 & 0x07; //uint64 y7 = 8 * y6; //uint8 y8 = uint8(m[i]); //uint64 y9 = uint64(y8); //uint64 y = y9 << y7; // //x ^= y; /////////////////////////////////////////////////////////////////////////// shake256_context64[(shake256_context64[25] + i) >> 3] ^= (uint64(uint8(m[i])) << (8 * ((shake256_context64[25] + i) & 0x07))); } mlen -= uint32(r - shake256_context64[25]); m += (r - shake256_context64[25]); shake256_context64[25] = 0; // Input parameters supplied in member variable shake256_context64. // Output values are written to the same member variable. KeccakF1600_StatePermute(); } for (i = 0; i < mlen; i++) { shake256_context64[(shake256_context64[25] + i) >> 3] ^= (uint64(uint8(m[i])) << (8 * ((shake256_context64[25] + i) & 0x07))); } shake256_context64[25] += mlen; } /************************************************* * Name: keccak_inc_finalize * * Description: Finalizes Keccak absorb phase, prepares for squeezing * * Arguments: - uint32 r : rate in bytes (e.g., 168 for SHAKE128) * - uint8 p : domain-separation byte for different Keccak-derived functions **************************************************/ //////////////////////////////////////// // //////////////////////////////////////// function keccak_inc_finalize(uint32 r, uint8 p) public payable { //fprintf(stdout, "TRACE: keccak_inc_finalize()\n"); shake256_context64[shake256_context64[25] >> 3] ^= uint64(p) << (8 * (shake256_context64[25] & 0x07)); shake256_context64[(r - 1) >> 3] ^= (uint64(128) << (8 * ((r - 1) & 0x07))); shake256_context64[25] = 0; } //////////////////////////////////////// // //////////////////////////////////////// function keccak_inc_squeeze(/*uint8* h, */ uint32 outlen, uint32 r) private pure returns (bytes memory h) { //fprintf(stdout, "TRACE: keccak_inc_squeeze()\n"); uint32 i; for (i = 0; i < outlen && i < shake256_context64[25]; i++) { h[i] = uint8(shake256_context64[(r - shake256_context64[25] + i) >> 3] >> (8 * ((r - shake256_context64[25] + i) & 0x07))); } h += i; outlen -= i; shake256_context64[25] -= i; while (outlen > 0) { // Input parameters supplied in member variable shake256_context64. // Output values are written to the same member variable. KeccakF1600_StatePermute(shake256_context64); for (i = 0; i < outlen && i < r; i++) { h[i] = uint8(shake256_context64[i >> 3] >> (8 * (i & 0x07))); } h += i; outlen -= i; shake256_context64[25] = r - i; } r = r; for (i = 0; i < outlen; i++) { h[i] = 0xAA; } } /////////////////////////////////////// // Implementation: OQS_SHA3_shake256_inc /////////////////////////////////////// //////////////////////////////////////// // //////////////////////////////////////// function OQS_SHA3_shake256_inc_init() public payable { int16 ii; //fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_init()\n"); for (ii=0; ii < CTX_ELEMENTS; ii++) shake256_context64[uint256(ii)] = 0; keccak_inc_init(); } //////////////////////////////////////// // //////////////////////////////////////// function OQS_SHA3_shake256_inc_absorb(bytes memory input, uint32 inlen) public pure { //fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_absorb()\n"); keccak_inc_absorb(SHAKE256_RATE, input, inlen); } //////////////////////////////////////// // //////////////////////////////////////// function OQS_SHA3_shake256_inc_finalize() public payable { //fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_finalize()\n"); keccak_inc_finalize(SHAKE256_RATE, 0x1F); } //////////////////////////////////////// // //////////////////////////////////////// function OQS_SHA3_shake256_inc_squeeze(/*uint8* output,*/ uint32 outlen) public pure returns (bytes memory output) { //fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_squeeze()\n"); output = keccak_inc_squeeze(outlen, SHAKE256_RATE); } //////////////////////////////////////// // //////////////////////////////////////// function OQS_SHA3_shake256_inc_ctx_release() public payable { int16 ii; //fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_ctx_release()\n"); // Blat over any sensitive data for (ii=0; ii < CTX_ELEMENTS; ii++) shake256_context64[uint256(ii)] = 0; } //} // ==== sha3_c.c END ===================================================================================================================== // ==== common.c BEGIN ===================================================================================================================== //contract lib_falcon_common //{ uint16[11] overtab = [ 0, /* unused */ 65, 67, 71, 77, 86, 100, 122, 154, 205, 287 ]; //////////////////////////////////////// // //////////////////////////////////////// function PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(bytes memory /*uint16**/ x, uint32 logn, bytes memory /* uint8 * */ workingStorage) public view { uint32 n; uint32 n2; uint32 u; uint32 m; uint32 p; uint32 over; //bytes memory /* uint16* */ tt1; uint16[63] memory tt2; //fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_hash_to_point_ct() ENTRY\n"); n = uint32(1) << logn; n2 = n << 1; over = overtab[logn]; m = n + over; // tt1 = (uint16 *)workingStorage; for (u = 0; u < m; u++) { uint8[2] memory buf; uint32 w; uint32 wr; OQS_SHA3_shake256_inc_squeeze(/*buf,*/ 2 /*sizeof(buf)*/); w = (uint32(buf[0]) << 8) | uint32(buf[1]); wr = w - (uint32(24578) & (((w - 24578) >> 31) - 1)); wr = wr - (uint32(24578) & (((wr - 24578) >> 31) - 1)); wr = wr - (uint32(12289) & (((wr - 12289) >> 31) - 1)); wr |= ((w - 61445) >> 31) - 1; if (u < n) { byte_array_uint16_set(x,u,uint16(wr)); //x[u] = uint16(wr); } else if (u < n2) { byte_array_uint16_set(workingStorage, (u-n), uint16(wr)); //tt1[u - n] = uint16(wr); } else { tt2[u - n2] = uint16(wr); } } for (p = 1; p <= over; p <<= 1) { uint32 v; v = 0; for (u = 0; u < m; u++) { uint16 *s; uint16 *d; uint32 j; uint32 sv; uint32 dv; uint32 mk; if (u < n) { s = &x[u]; } else if (u < n2) { s = &tt1[u - n]; } else { s = &tt2[u - n2]; } sv = *s; j = u - v; mk = (sv >> 15) - 1U; v -= mk; if (u < p) { continue; } if ((u - p) < n) { d = &x[u - p]; } else if ((u - p) < n2) { d = &tt1[(u - p) - n]; } else { d = &tt2[(u - p) - n2]; } dv = *d; mk &= -(((j & p) + 0x01FF) >> 9); *s = uint16(sv ^ (mk & (sv ^ dv))); *d = uint16(dv ^ (mk & (sv ^ dv))); } } //fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_hash_to_point_ct() EXIT\n"); } //////////////////////////////////////// // //////////////////////////////////////// function PQCLEAN_FALCON512_CLEAN_is_short(bytes memory /* const int16_t * */ s1, bytes memory /* const int16_t* */ s2, uint32 logn) public pure returns (int32) { uint32 n; uint32 u; uint32 s; uint32 ng; n = uint32(1) << logn; s = 0; ng = 0; for (u = 0; u < n; u++) { int32 z; z = byte_array_uint16_get(s1,u); //z = s1[u]; s += uint32(z * z); ng |= s; z = byte_array_uint16_get(s2,u); //z = s2[u]; s += uint32(z * z); ng |= s; } s |= -(ng >> 31); //return s < ((uint32(7085) * uint32(12289)) >> (10 - logn)); uint32 val = ((uint32(7085) * uint32(12289)) >> (10 - logn)); if (s < val) return 1; return 0; } //} // ==== common.c END ===================================================================================================================== // ==== codec.c BEGIN ===================================================================================================================== //library lib_falcon_codec //{ //////////////////////////////////////// // //////////////////////////////////////// function PQCLEAN_FALCON512_CLEAN_modq_decode(bytes memory /*uint16 **/ x, uint16 logn, bytes memory /*const void**/ In, uint32 max_In_len) public pure returns (uint32) { uint32 n; uint32 In_len; uint32 u; //uint8 * buf; uint32 buf_ndx; uint32 acc; uint32 acc_len; n = uint32(1) << logn; In_len = ((n * 14) + 7) >> 3; if (In_len > max_In_len) { return 0; } //buf = In; buf_ndx = 0; acc = 0; acc_len = 0; u = 0; while (u < n) { acc = (acc << 8) | uint32(uint8(In[buf_ndx++])); // acc = (acc << 8) | (*buf++); acc_len += 8; if (acc_len >= 14) { uint32 w; acc_len -= 14; w = (acc >> acc_len) & 0x3FFF; if (w >= 12289) { return 0; } byte_array_uint16_set(x,u,uint16(w)); //x[u++] = uint16(w); u++; } } if ((acc & ((uint32(1) << acc_len) - 1)) != 0) { return 0; } return In_len; } //////////////////////////////////////// // //////////////////////////////////////// function PQCLEAN_FALCON512_CLEAN_comp_decode(bytes memory /*int16_t**/ x, uint32 logn, bytes memory /*const void**/ In, uint32 max_In_len) public pure returns (uint32) { //const uint8 *buf; uint32 buf_ndx; uint32 n; uint32 u; uint32 v; uint32 acc; uint acc_len; n = uint32(1) << logn; //buf = In; buf_ndx = 0; acc = 0; acc_len = 0; v = 0; for (u = 0; u < n; u++) { uint b; uint s; uint m; if (v >= max_In_len) { return 0; } acc = (acc << 8) | uint32(uint8(In[buf_ndx++])); // acc = (acc << 8) | uint32(buf[v++]); b = acc >> acc_len; s = b & 128; m = b & 127; for (;;) { if (acc_len == 0) { if (v >= max_In_len) { return 0; } acc = (acc << 8) | uint32(uint8(In[buf_ndx++])); // acc = (acc << 8) | uint32(buf[v++]); acc_len = 8; } acc_len--; if (((acc >> acc_len) & 1) != 0) { break; } m += 128; if (m > 2047) { return 0; } } int16 val = int16((s!=0) ? -int(m) : int(m)); byte_array_int16_set(x,u,val); // x[u] = int16(s ? -int(m) : int(m)); } return v; } //} // ==== codec.c END ===================================================================================================================== // ==== vrfy_constants.h BEGIN ===================================================================================================================== // Useful reference: // https://medium.com/@jeancvllr/solidity-tutorial-all-about-bytes-9d88fdb22676 // https://medium.com/@jeancvllr/solidity-tutorial-all-about-libraries-762e5a3692f9 //contract lib_falcon_vrfy_constants //{ //////////////////////////////////////// // Constants for NTT. // n = 2^logn (2 <= n <= 1024) // phi = X^n + 1 // q = 12289 // q0i = -1/q mod 2^16 // R = 2^16 mod q // R2 = 2^32 mod q //////////////////////////////////////// uint32 constant Q = 12289; uint32 constant Q0I = 12287; uint32 constant R = 4091; uint32 constant R2 = 10952; //////////////////////////////////////// // Table for NTT, binary case: // GMb[x] = R*(g^rev(x)) mod q // where g = 7 (it is a 2048-th primitive root of 1 modulo q) // and rev() is the bit-reversal function over 10 bits. //////////////////////////////////////// uint16[1024] GMb = [ 4091, 7888, 11060, 11208, 6960, 4342, 6275, 9759, 1591, 6399, 9477, 5266, 586, 5825, 7538, 9710, 1134, 6407, 1711, 965, 7099, 7674, 3743, 6442, 10414, 8100, 1885, 1688, 1364, 10329, 10164, 9180, 12210, 6240, 997, 117, 4783, 4407, 1549, 7072, 2829, 6458, 4431, 8877, 7144, 2564, 5664, 4042, 12189, 432, 10751, 1237, 7610, 1534, 3983, 7863, 2181, 6308, 8720, 6570, 4843, 1690, 14, 3872, 5569, 9368, 12163, 2019, 7543, 2315, 4673, 7340, 1553, 1156, 8401, 11389, 1020, 2967, 10772, 7045, 3316, 11236, 5285, 11578, 10637, 10086, 9493, 6180, 9277, 6130, 3323, 883, 10469, 489, 1502, 2851, 11061, 9729, 2742, 12241, 4970, 10481, 10078, 1195, 730, 1762, 3854, 2030, 5892, 10922, 9020, 5274, 9179, 3604, 3782, 10206, 3180, 3467, 4668, 2446, 7613, 9386, 834, 7703, 6836, 3403, 5351, 12276, 3580, 1739, 10820, 9787, 10209, 4070, 12250, 8525, 10401, 2749, 7338, 10574, 6040, 943, 9330, 1477, 6865, 9668, 3585, 6633, 12145, 4063, 3684, 7680, 8188, 6902, 3533, 9807, 6090, 727, 10099, 7003, 6945, 1949, 9731, 10559, 6057, 378, 7871, 8763, 8901, 9229, 8846, 4551, 9589, 11664, 7630, 8821, 5680, 4956, 6251, 8388, 10156, 8723, 2341, 3159, 1467, 5460, 8553, 7783, 2649, 2320, 9036, 6188, 737, 3698, 4699, 5753, 9046, 3687, 16, 914, 5186, 10531, 4552, 1964, 3509, 8436, 7516, 5381, 10733, 3281, 7037, 1060, 2895, 7156, 8887, 5357, 6409, 8197, 2962, 6375, 5064, 6634, 5625, 278, 932, 10229, 8927, 7642, 351, 9298, 237, 5858, 7692, 3146, 12126, 7586, 2053, 11285, 3802, 5204, 4602, 1748, 11300, 340, 3711, 4614, 300, 10993, 5070, 10049, 11616, 12247, 7421, 10707, 5746, 5654, 3835, 5553, 1224, 8476, 9237, 3845, 250, 11209, 4225, 6326, 9680, 12254, 4136, 2778, 692, 8808, 6410, 6718, 10105, 10418, 3759, 7356, 11361, 8433, 6437, 3652, 6342, 8978, 5391, 2272, 6476, 7416, 8418, 10824, 11986, 5733, 876, 7030, 2167, 2436, 3442, 9217, 8206, 4858, 5964, 2746, 7178, 1434, 7389, 8879, 10661, 11457, 4220, 1432, 10832, 4328, 8557, 1867, 9454, 2416, 3816, 9076, 686, 5393, 2523, 4339, 6115, 619, 937, 2834, 7775, 3279, 2363, 7488, 6112, 5056, 824, 10204, 11690, 1113, 2727, 9848, 896, 2028, 5075, 2654, 10464, 7884, 12169, 5434, 3070, 6400, 9132, 11672, 12153, 4520, 1273, 9739, 11468, 9937, 10039, 9720, 2262, 9399, 11192, 315, 4511, 1158, 6061, 6751, 11865, 357, 7367, 4550, 983, 8534, 8352, 10126, 7530, 9253, 4367, 5221, 3999, 8777, 3161, 6990, 4130, 11652, 3374, 11477, 1753, 292, 8681, 2806, 10378, 12188, 5800, 11811, 3181, 1988, 1024, 9340, 2477, 10928, 4582, 6750, 3619, 5503, 5233, 2463, 8470, 7650, 7964, 6395, 1071, 1272, 3474, 11045, 3291, 11344, 8502, 9478, 9837, 1253, 1857, 6233, 4720, 11561, 6034, 9817, 3339, 1797, 2879, 6242, 5200, 2114, 7962, 9353, 11363, 5475, 6084, 9601, 4108, 7323, 10438, 9471, 1271, 408, 6911, 3079, 360, 8276, 11535, 9156, 9049, 11539, 850, 8617, 784, 7919, 8334, 12170, 1846, 10213, 12184, 7827, 11903, 5600, 9779, 1012, 721, 2784, 6676, 6552, 5348, 4424, 6816, 8405, 9959, 5150, 2356, 5552, 5267, 1333, 8801, 9661, 7308, 5788, 4910, 909, 11613, 4395, 8238, 6686, 4302, 3044, 2285, 12249, 1963, 9216, 4296, 11918, 695, 4371, 9793, 4884, 2411, 10230, 2650, 841, 3890, 10231, 7248, 8505, 11196, 6688, 4059, 6060, 3686, 4722, 11853, 5816, 7058, 6868, 11137, 7926, 4894, 12284, 4102, 3908, 3610, 6525, 7938, 7982, 11977, 6755, 537, 4562, 1623, 8227, 11453, 7544, 906, 11816, 9548, 10858, 9703, 2815, 11736, 6813, 6979, 819, 8903, 6271, 10843, 348, 7514, 8339, 6439, 694, 852, 5659, 2781, 3716, 11589, 3024, 1523, 8659, 4114, 10738, 3303, 5885, 2978, 7289, 11884, 9123, 9323, 11830, 98, 2526, 2116, 4131, 11407, 1844, 3645, 3916, 8133, 2224, 10871, 8092, 9651, 5989, 7140, 8480, 1670, 159, 10923, 4918, 128, 7312, 725, 9157, 5006, 6393, 3494, 6043, 10972, 6181, 11838, 3423, 10514, 7668, 3693, 6658, 6905, 11953, 10212, 11922, 9101, 8365, 5110, 45, 2400, 1921, 4377, 2720, 1695, 51, 2808, 650, 1896, 9997, 9971, 11980, 8098, 4833, 4135, 4257, 5838, 4765, 10985, 11532, 590, 12198, 482, 12173, 2006, 7064, 10018, 3912, 12016, 10519, 11362, 6954, 2210, 284, 5413, 6601, 3865, 10339, 11188, 6231, 517, 9564, 11281, 3863, 1210, 4604, 8160, 11447, 153, 7204, 5763, 5089, 9248, 12154, 11748, 1354, 6672, 179, 5532, 2646, 5941, 12185, 862, 3158, 477, 7279, 5678, 7914, 4254, 302, 2893, 10114, 6890, 9560, 9647, 11905, 4098, 9824, 10269, 1353, 10715, 5325, 6254, 3951, 1807, 6449, 5159, 1308, 8315, 3404, 1877, 1231, 112, 6398, 11724, 12272, 7286, 1459, 12274, 9896, 3456, 800, 1397, 10678, 103, 7420, 7976, 936, 764, 632, 7996, 8223, 8445, 7758, 10870, 9571, 2508, 1946, 6524, 10158, 1044, 4338, 2457, 3641, 1659, 4139, 4688, 9733, 11148, 3946, 2082, 5261, 2036, 11850, 7636, 12236, 5366, 2380, 1399, 7720, 2100, 3217, 10912, 8898, 7578, 11995, 2791, 1215, 3355, 2711, 2267, 2004, 8568, 10176, 3214, 2337, 1750, 4729, 4997, 7415, 6315, 12044, 4374, 7157, 4844, 211, 8003, 10159, 9290, 11481, 1735, 2336, 5793, 9875, 8192, 986, 7527, 1401, 870, 3615, 8465, 2756, 9770, 2034, 10168, 3264, 6132, 54, 2880, 4763, 11805, 3074, 8286, 9428, 4881, 6933, 1090, 10038, 2567, 708, 893, 6465, 4962, 10024, 2090, 5718, 10743, 780, 4733, 4623, 2134, 2087, 4802, 884, 5372, 5795, 5938, 4333, 6559, 7549, 5269, 10664, 4252, 3260, 5917, 10814, 5768, 9983, 8096, 7791, 6800, 7491, 6272, 1907, 10947, 6289, 11803, 6032, 11449, 1171, 9201, 7933, 2479, 7970, 11337, 7062, 8911, 6728, 6542, 8114, 8828, 6595, 3545, 4348, 4610, 2205, 6999, 8106, 5560, 10390, 9321, 2499, 2413, 7272, 6881, 10582, 9308, 9437, 3554, 3326, 5991, 11969, 3415, 12283, 9838, 12063, 4332, 7830, 11329, 6605, 12271, 2044, 11611, 7353, 11201, 11582, 3733, 8943, 9978, 1627, 7168, 3935, 5050, 2762, 7496, 10383, 755, 1654, 12053, 4952, 10134, 4394, 6592, 7898, 7497, 8904, 12029, 3581, 10748, 5674, 10358, 4901, 7414, 8771, 710, 6764, 8462, 7193, 5371, 7274, 11084, 290, 7864, 6827, 11822, 2509, 6578, 4026, 5807, 1458, 5721, 5762, 4178, 2105, 11621, 4852, 8897, 2856, 11510, 9264, 2520, 8776, 7011, 2647, 1898, 7039, 5950, 11163, 5488, 6277, 9182, 11456, 633, 10046, 11554, 5633, 9587, 2333, 7008, 7084, 5047, 7199, 9865, 8997, 569, 6390, 10845, 9679, 8268, 11472, 4203, 1997, 2, 9331, 162, 6182, 2000, 3649, 9792, 6363, 7557, 6187, 8510, 9935, 5536, 9019, 3706, 12009, 1452, 3067, 5494, 9692, 4865, 6019, 7106, 9610, 4588, 10165, 6261, 5887, 2652, 10172, 1580, 10379, 4638, 9949 ]; //////////////////////////////////////// // Table for inverse NTT, binary case: // iGMb[x] = R*((1/g)^rev(x)) mod q // Since g = 7, 1/g = 8778 mod 12289. //////////////////////////////////////// uint16[1024] iGMb = [ 4091, 4401, 1081, 1229, 2530, 6014, 7947, 5329, 2579, 4751, 6464, 11703, 7023, 2812, 5890, 10698, 3109, 2125, 1960, 10925, 10601, 10404, 4189, 1875, 5847, 8546, 4615, 5190, 11324, 10578, 5882, 11155, 8417, 12275, 10599, 7446, 5719, 3569, 5981, 10108, 4426, 8306, 10755, 4679, 11052, 1538, 11857, 100, 8247, 6625, 9725, 5145, 3412, 7858, 5831, 9460, 5217, 10740, 7882, 7506, 12172, 11292, 6049, 79, 13, 6938, 8886, 5453, 4586, 11455, 2903, 4676, 9843, 7621, 8822, 9109, 2083, 8507, 8685, 3110, 7015, 3269, 1367, 6397, 10259, 8435, 10527, 11559, 11094, 2211, 1808, 7319, 48, 9547, 2560, 1228, 9438, 10787, 11800, 1820, 11406, 8966, 6159, 3012, 6109, 2796, 2203, 1652, 711, 7004, 1053, 8973, 5244, 1517, 9322, 11269, 900, 3888, 11133, 10736, 4949, 7616, 9974, 4746, 10270, 126, 2921, 6720, 6635, 6543, 1582, 4868, 42, 673, 2240, 7219, 1296, 11989, 7675, 8578, 11949, 989, 10541, 7687, 7085, 8487, 1004, 10236, 4703, 163, 9143, 4597, 6431, 12052, 2991, 11938, 4647, 3362, 2060, 11357, 12011, 6664, 5655, 7225, 5914, 9327, 4092, 5880, 6932, 3402, 5133, 9394, 11229, 5252, 9008, 1556, 6908, 4773, 3853, 8780, 10325, 7737, 1758, 7103, 11375, 12273, 8602, 3243, 6536, 7590, 8591, 11552, 6101, 3253, 9969, 9640, 4506, 3736, 6829, 10822, 9130, 9948, 3566, 2133, 3901, 6038, 7333, 6609, 3468, 4659, 625, 2700, 7738, 3443, 3060, 3388, 3526, 4418, 11911, 6232, 1730, 2558, 10340, 5344, 5286, 2190, 11562, 6199, 2482, 8756, 5387, 4101, 4609, 8605, 8226, 144, 5656, 8704, 2621, 5424, 10812, 2959, 11346, 6249, 1715, 4951, 9540, 1888, 3764, 39, 8219, 2080, 2502, 1469, 10550, 8709, 5601, 1093, 3784, 5041, 2058, 8399, 11448, 9639, 2059, 9878, 7405, 2496, 7918, 11594, 371, 7993, 3073, 10326, 40, 10004, 9245, 7987, 5603, 4051, 7894, 676, 11380, 7379, 6501, 4981, 2628, 3488, 10956, 7022, 6737, 9933, 7139, 2330, 3884, 5473, 7865, 6941, 5737, 5613, 9505, 11568, 11277, 2510, 6689, 386, 4462, 105, 2076, 10443, 119, 3955, 4370, 11505, 3672, 11439, 750, 3240, 3133, 754, 4013, 11929, 9210, 5378, 11881, 11018, 2818, 1851, 4966, 8181, 2688, 6205, 6814, 926, 2936, 4327, 10175, 7089, 6047, 9410, 10492, 8950, 2472, 6255, 728, 7569, 6056, 10432, 11036, 2452, 2811, 3787, 945, 8998, 1244, 8815, 11017, 11218, 5894, 4325, 4639, 3819, 9826, 7056, 6786, 8670, 5539, 7707, 1361, 9812, 2949, 11265, 10301, 9108, 478, 6489, 101, 1911, 9483, 3608, 11997, 10536, 812, 8915, 637, 8159, 5299, 9128, 3512, 8290, 7068, 7922, 3036, 4759, 2163, 3937, 3755, 11306, 7739, 4922, 11932, 424, 5538, 6228, 11131, 7778, 11974, 1097, 2890, 10027, 2569, 2250, 2352, 821, 2550, 11016, 7769, 136, 617, 3157, 5889, 9219, 6855, 120, 4405, 1825, 9635, 7214, 10261, 11393, 2441, 9562, 11176, 599, 2085, 11465, 7233, 6177, 4801, 9926, 9010, 4514, 9455, 11352, 11670, 6174, 7950, 9766, 6896, 11603, 3213, 8473, 9873, 2835, 10422, 3732, 7961, 1457, 10857, 8069, 832, 1628, 3410, 4900, 10855, 5111, 9543, 6325, 7431, 4083, 3072, 8847, 9853, 10122, 5259, 11413, 6556, 303, 1465, 3871, 4873, 5813, 10017, 6898, 3311, 5947, 8637, 5852, 3856, 928, 4933, 8530, 1871, 2184, 5571, 5879, 3481, 11597, 9511, 8153, 35, 2609, 5963, 8064, 1080, 12039, 8444, 3052, 3813, 11065, 6736, 8454, 2340, 7651, 1910, 10709, 2117, 9637, 6402, 6028, 2124, 7701, 2679, 5183, 6270, 7424, 2597, 6795, 9222, 10837, 280, 8583, 3270, 6753, 2354, 3779, 6102, 4732, 5926, 2497, 8640, 10289, 6107, 12127, 2958, 12287, 10292, 8086, 817, 4021, 2610, 1444, 5899, 11720, 3292, 2424, 5090, 7242, 5205, 5281, 9956, 2702, 6656, 735, 2243, 11656, 833, 3107, 6012, 6801, 1126, 6339, 5250, 10391, 9642, 5278, 3513, 9769, 3025, 779, 9433, 3392, 7437, 668, 10184, 8111, 6527, 6568, 10831, 6482, 8263, 5711, 9780, 467, 5462, 4425, 11999, 1205, 5015, 6918, 5096, 3827, 5525, 11579, 3518, 4875, 7388, 1931, 6615, 1541, 8708, 260, 3385, 4792, 4391, 5697, 7895, 2155, 7337, 236, 10635, 11534, 1906, 4793, 9527, 7239, 8354, 5121, 10662, 2311, 3346, 8556, 707, 1088, 4936, 678, 10245, 18, 5684, 960, 4459, 7957, 226, 2451, 6, 8874, 320, 6298, 8963, 8735, 2852, 2981, 1707, 5408, 5017, 9876, 9790, 2968, 1899, 6729, 4183, 5290, 10084, 7679, 7941, 8744, 5694, 3461, 4175, 5747, 5561, 3378, 5227, 952, 4319, 9810, 4356, 3088, 11118, 840, 6257, 486, 6000, 1342, 10382, 6017, 4798, 5489, 4498, 4193, 2306, 6521, 1475, 6372, 9029, 8037, 1625, 7020, 4740, 5730, 7956, 6351, 6494, 6917, 11405, 7487, 10202, 10155, 7666, 7556, 11509, 1546, 6571, 10199, 2265, 7327, 5824, 11396, 11581, 9722, 2251, 11199, 5356, 7408, 2861, 4003, 9215, 484, 7526, 9409, 12235, 6157, 9025, 2121, 10255, 2519, 9533, 3824, 8674, 11419, 10888, 4762, 11303, 4097, 2414, 6496, 9953, 10554, 808, 2999, 2130, 4286, 12078, 7445, 5132, 7915, 245, 5974, 4874, 7292, 7560, 10539, 9952, 9075, 2113, 3721, 10285, 10022, 9578, 8934, 11074, 9498, 294, 4711, 3391, 1377, 9072, 10189, 4569, 10890, 9909, 6923, 53, 4653, 439, 10253, 7028, 10207, 8343, 1141, 2556, 7601, 8150, 10630, 8648, 9832, 7951, 11245, 2131, 5765, 10343, 9781, 2718, 1419, 4531, 3844, 4066, 4293, 11657, 11525, 11353, 4313, 4869, 12186, 1611, 10892, 11489, 8833, 2393, 15, 10830, 5003, 17, 565, 5891, 12177, 11058, 10412, 8885, 3974, 10981, 7130, 5840, 10482, 8338, 6035, 6964, 1574, 10936, 2020, 2465, 8191, 384, 2642, 2729, 5399, 2175, 9396, 11987, 8035, 4375, 6611, 5010, 11812, 9131, 11427, 104, 6348, 9643, 6757, 12110, 5617, 10935, 541, 135, 3041, 7200, 6526, 5085, 12136, 842, 4129, 7685, 11079, 8426, 1008, 2725, 11772, 6058, 1101, 1950, 8424, 5688, 6876, 12005, 10079, 5335, 927, 1770, 273, 8377, 2271, 5225, 10283, 116, 11807, 91, 11699, 757, 1304, 7524, 6451, 8032, 8154, 7456, 4191, 309, 2318, 2292, 10393, 11639, 9481, 12238, 10594, 9569, 7912, 10368, 9889, 12244, 7179, 3924, 3188, 367, 2077, 336, 5384, 5631, 8596, 4621, 1775, 8866, 451, 6108, 1317, 6246, 8795, 5896, 7283, 3132, 11564, 4977, 12161, 7371, 1366, 12130, 10619, 3809, 5149, 6300, 2638, 4197, 1418, 10065, 4156, 8373, 8644, 10445, 882, 8158, 10173, 9763, 12191, 459, 2966, 3166, 405, 5000, 9311, 6404, 8986, 1551, 8175, 3630, 10766, 9265, 700, 8573, 9508, 6630, 11437, 11595, 5850, 3950, 4775, 11941, 1446, 6018, 3386, 11470, 5310, 5476, 553, 9474, 2586, 1431, 2741, 473, 11383, 4745, 836, 4062, 10666, 7727, 11752, 5534, 312, 4307, 4351, 5764, 8679, 8381, 8187, 5, 7395, 4363, 1152, 5421, 5231, 6473, 436, 7567, 8603, 6229, 8230 ]; //} // ==== vrfy_constants.h END ===================================================================================================================== // ==== vrfy.c BEGIN ===================================================================================================================== //import "lib_falcon_common.sol"; //import "lib_falcon_vrfy_constants.sol"; //import GMb from "lib_falcon_vrfy_constants.sol"; //library lib_falcon_vrfy //{ //uint32 Q = 1; // TODO: Where do I get Q //uint32 Q0I = 1; // TODO: Where do I get Q0I //uint32 R = 1; // TODO: Where do I get R //uint32 R2 = 1; // TODO: Where do I get R2 //uint32[2] GMb = [1,2]; // TODO: Where do I get GMb //uint32[2] iGMb = [1,2]; // TODO: Where do I get iGMb //////////////////////////////////////// // Addition modulo q. Operands must be in the 0..q-1 range. //////////////////////////////////////// function mq_add(uint32 x, uint32 y) private pure returns (uint32 result) { uint32 d; d = x + y - Q; d += Q & -(d >> 31); result = d; } //////////////////////////////////////// // Subtraction modulo q. Operands must be in the 0..q-1 range. //////////////////////////////////////// function mq_sub(uint32 x, uint32 y) private pure returns (uint32 result) { // As in mq_add(), we use a conditional addition to ensure the result is in the 0..q-1 range. uint32 d; d = x - y; d += Q & -(d >> 31); return d; } //////////////////////////////////////// // Division by 2 modulo q. Operand must be in the 0..q-1 range. //////////////////////////////////////// function mq_rshift1(uint32 x) private pure returns (uint32 result) { x += Q & -(x & 1); return (x >> 1); } //////////////////////////////////////// // Montgomery multiplication modulo q. If we set R = 2^16 mod q, then this function computes: x * y / R mod q // Operands must be in the 0..q-1 range. //////////////////////////////////////// function mq_montymul(uint32 x, uint32 y) private pure returns (uint32 result) { uint32 z; uint32 w; z = x * y; w = ((z * Q0I) & 0xFFFF) * Q; z = (z + w) >> 16; z -= Q; z += Q & -(z >> 31); return z; } //////////////////////////////////////// // Montgomery squaring (computes (x^2)/R). //////////////////////////////////////// function mq_montysqr(uint32 x) private pure returns (uint32 result) { return mq_montymul(x, x); } //////////////////////////////////////// // Divide x by y modulo q = 12289. //////////////////////////////////////// function mq_div_12289(uint32 x, uint32 y) private pure returns (uint32 result) { /*$off*/ uint32 y0; uint32 y1; uint32 y2; uint32 y3; uint32 y4; uint32 y5; uint32 y6; uint32 y7; uint32 y8; uint32 y9; uint32 y10; uint32 y11; uint32 y12; uint32 y13; uint32 y14; uint32 y15; uint32 y16; uint32 y17; uint32 y18; /*$on*/ y0 = mq_montymul(y, R2); y1 = mq_montysqr(y0); y2 = mq_montymul(y1, y0); y3 = mq_montymul(y2, y1); y4 = mq_montysqr(y3); y5 = mq_montysqr(y4); y6 = mq_montysqr(y5); y7 = mq_montysqr(y6); y8 = mq_montysqr(y7); y9 = mq_montymul(y8, y2); y10 = mq_montymul(y9, y8); y11 = mq_montysqr(y10); y12 = mq_montysqr(y11); y13 = mq_montymul(y12, y9); y14 = mq_montysqr(y13); y15 = mq_montysqr(y14); y16 = mq_montymul(y15, y10); y17 = mq_montysqr(y16); y18 = mq_montymul(y17, y0); return mq_montymul(y18, x); } //////////////////////////////////////// // Compute NTT on a ring element. //////////////////////////////////////// function mq_NTT(bytes memory /*uint16**/ a, uint32 logn) private pure { uint32 n; uint32 t; uint32 m; n = uint32(1) << logn; t = n; for (m = 1; m < n; m <<= 1) { uint32 ht; uint32 i; uint32 j1; ht = t >> 1; j1 = 0; for (i = 0; i < m; i++) { uint32 j; uint32 j2; uint32 s; s = GMb[m + i]; j2 = j1 + ht; for (j = j1; j < j2; j++) { uint32 u; uint32 v; uint32 tmp32; uint16 tmp16; u = byte_array_uint16_get(a,j); // u = a[j]; tmp32 = byte_array_uint16_get(a,j + ht); // tmp = a[j + ht]; v = mq_montymul(tmp32, s); // v = mq_montymul(a[j + ht], s); tmp16 = uint16(mq_add(u, v)); byte_array_uint16_set(a,j ,tmp16); // a[j] = uint16(mq_add(u, v)); tmp16 = uint16(mq_sub(u, v)); byte_array_uint16_set(a,j+ht,tmp16); // a[j + ht] = uint16(mq_sub(u, v)); } j1 += t; } t = ht; } } //////////////////////////////////////// // Compute the inverse NTT on a ring element, binary case. //////////////////////////////////////// function mq_iNTT(bytes memory /*uint16**/ a, uint32 logn) private pure { uint32 n; uint32 t; uint32 m; uint32 ni; n = uint32(1) << logn; t = 1; m = n; while (m > 1) { uint32 hm; uint32 dt; uint32 i; uint32 j1; hm = m >> 1; dt = t << 1; j1 = 0; for (i = 0; i < hm; i++) { uint32 j; uint32 j2; uint32 s; j2 = j1 + t; s = iGMb[hm + i]; for (j = j1; j < j2; j++) { uint32 u; uint32 v; uint32 w; uint16 tmp16; u = byte_array_uint16_get(a,j ); // u = a[j]; v = byte_array_uint16_get(a,j+t); // v = a[j + t]; tmp16 = uint16(mq_add(u, v)); byte_array_uint16_set(a,j,tmp16); // a[j] = uint16(mq_add(u, v)); w = mq_sub(u, v); tmp16 = uint16(mq_montymul(w, s)); byte_array_uint16_set(a,j+t,tmp16); // a[j + t] = uint16(mq_montymul(w, s)); } j1 += dt; } t = dt; m = hm; } ni = R; for (m = n; m > 1; m >>= 1) { ni = mq_rshift1(ni); } for (m = 0; m < n; m++) { uint16 tmp1 = byte_array_uint16_get(a, m); // a[m]; uint16 tmp2 = uint16(mq_montymul(tmp1, ni)); byte_array_uint16_set(a,m,tmp2); // a[j + t] = uint16(mq_montymul(w, s)); } } //////////////////////////////////////// // Convert a polynomial (mod q) to Montgomery representation. //////////////////////////////////////// function mq_poly_tomonty(bytes memory /*uint16**/ f, uint32 logn) private pure { uint32 u; uint32 n; n = uint32(1) << logn; for (u = 0; u < n; u++) { uint16 tmp1 = byte_array_uint16_get(f,u); // f[u]; uint16 tmp2 = uint16(mq_montymul(tmp1, R2)); byte_array_uint16_set(f,u,tmp2); // f[u] = uint16(mq_montymul(f[u], R2)); } } //////////////////////////////////////// // Multiply two polynomials together (NTT representation, and using // a Montgomery multiplication). Result f*g is written over f. //////////////////////////////////////// function mq_poly_montymul_ntt(bytes memory /*uint16**/ f, bytes memory /*uint16**/ g, uint32 logn) private pure { uint32 u; uint32 n; n = uint32(1) << logn; for (u = 0; u < n; u++) { uint16 tmp1 = byte_array_uint16_get(f,u); uint16 tmp2 = byte_array_uint16_get(g,u); uint16 tmp16 = uint16(mq_montymul(tmp1, tmp2)); byte_array_uint16_set(f,u,tmp16); // f[u] = uint16(mq_montymul(f[u], g[u])); } } //////////////////////////////////////// // Subtract polynomial g from polynomial f. //////////////////////////////////////// function mq_poly_sub(bytes memory /*uint16**/ f, bytes memory /*uint16**/ g, uint32 logn) private pure { uint32 u; uint32 n; n = uint32(1) << logn; for (u = 0; u < n; u++) { uint16 tmp1 = byte_array_uint16_get(f,u); uint16 tmp2 = byte_array_uint16_get(g,u); uint16 tmp16 = uint16(mq_sub(tmp1, tmp2)); byte_array_uint16_set(f,u,tmp16); // f[u] = uint16(mq_sub(f[u], g[u])); } } /* ===================================================================== */ //////////////////////////////////////// // //////////////////////////////////////// function PQCLEAN_FALCON512_CLEAN_to_ntt_monty(bytes memory /*uint16**/ h, uint32 logn) public pure { //fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_to_ntt_monty() ENTRY\n"); mq_NTT(h, logn); mq_poly_tomonty(h, logn); } //////////////////////////////////////// // //////////////////////////////////////// function PQCLEAN_FALCON512_CLEAN_verify_raw(bytes memory /*uint16**/ c0, bytes memory /*int16_t **/ s2, bytes memory /*uint16**/ h, uint32 logn, bytes memory workingStorage) public pure returns (int result) { uint32 u; uint32 n; bytes memory /* uint16* */ tt; //fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_verify_raw() ENTRY\n"); n = uint32(1) << logn; tt = workingStorage; // tt = (uint16 *)workingStorage; // Reduce s2 elements modulo q ([0..q-1] range). for (u = 0; u < n; u++) { uint32 w; uint16 tmp1 = byte_array_uint16_get(s2,u); // w = uint32(s2[u]); w = uint32(tmp1); w += Q & -(w >> 31); byte_array_uint16_set(tt,u,uint16(w)); // tt[u] = uint16(w); } // Compute -s1 = s2*h - c0 mod phi mod q (in tt[]). mq_NTT(tt, logn); mq_poly_montymul_ntt(tt, h, logn); mq_iNTT(tt, logn); mq_poly_sub(tt, c0, logn); // Normalize -s1 elements into the [-q/2..q/2] range. for (u = 0; u < n; u++) { int32 w; uint16 tmp1 = byte_array_uint16_get(tt,u); // w = int32(tt[u]); w = int32(tmp1); w -= int32(Q & -(((Q >> 1) - uint32(w)) >> 31)); byte_array_int16_set(tt,u,int16(w)); // tt[u] = int16(w); // ((int16 *)tt)[u] = (int16)w; } // Signature is valid if and only if the aggregate (-s1,s2) vector is short enough. int rc = PQCLEAN_FALCON512_CLEAN_is_short(tt, s2, logn); //fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_verify_raw() EXIT\n"); return rc; } //} // ==== vrfy.c END ===================================================================================================================== // ==== pqclean.c BEGIN ===================================================================================================================== // https://manojpramesh.github.io/solidity-cheatsheet/ uint16 constant PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES = 1281; uint16 constant PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES = 897; uint16 constant PQCLEAN_FALCON512_CLEAN_CRYPTO_SIGNATUREBYTES = 690; //import "falcon_sha3_c.sol"; //import * as falcon_sha3 from "lib_falcon_sha3_c.sol"; //import "falcon_sha3_c.sol" as falcon_sha3; //library lib_falcon_pqclean //{ //////////////////////////////////////// // //////////////////////////////////////// uint16 constant NONCELEN = 40; // ==================================================================== // Implementation // ==================================================================== //////////////////////////////////////// // // static int do_verify(const uint8_t* nonce, // const uint8_t* sigbuf, // size_t sigbuflen, // const uint8_t* m, // size_t mlen, // const uint8_t* pk) //////////////////////////////////////// function do_verify ( bytes memory /* uint8_t* */ nonce, bytes memory /* uint8_t* */ sigbuf, uint16 sigbuflen, bytes memory /* uint8_t* */ m, uint16 mlen, bytes memory /* uint8_t* */ pk ) public pure returns (int16) { uint8[2*512] memory workingStorage; // array of 1024 bytes uint16[512] memory h; uint16[512] memory hm; int16[512] memory sig; uint16 sz1; uint16 sz2; int16 rc; //fprintf(stdout, "INFO: do_verify() ENTRY\n"); /////////////////////////////////////////////// // Validate params if (uint8(pk[0]) != (0x00 + 9)) { return -3; } if (sigbuflen == 0) { return -5; } /////////////////////////////////////////////// // Decode public key. //fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_modq_decode()\n"); sz1 = PQCLEAN_FALCON512_CLEAN_modq_decode( h, 9, pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1); if (sz1 != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) { return -1; } //fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_to_ntt_monty()\n"); PQCLEAN_FALCON512_CLEAN_to_ntt_monty(h, 9); /////////////////////////////////////////////// // Decode signature. //fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_comp_decode()\n"); sz2 = PQCLEAN_FALCON512_CLEAN_comp_decode(sig, 9, sigbuf, sigbuflen); if (sz2 != sigbuflen) { return -6; } /////////////////////////////////////////////// // Hash nonce + message into a vector. OQS_SHA3_shake256_inc_init(); OQS_SHA3_shake256_inc_absorb(nonce, NONCELEN); OQS_SHA3_shake256_inc_absorb(m, mlen); OQS_SHA3_shake256_inc_finalize(); PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(hm, 9, workingStorage); OQS_SHA3_shake256_inc_ctx_release(); /////////////////////////////////////////////// // Verify signature. //fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_verify_raw()\n"); rc = PQCLEAN_FALCON512_CLEAN_verify_raw(hm, sig, h, 9, workingStorage); if (rc == 0) { return -7; } //fprintf(stdout, "INFO: do_verify() EXIT\n"); return 0; } //////////////////////////////////////// // // int PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(const uint8_t* sig, // size_t siglen, // const uint8_t* m, // size_t mlen, // const uint8_t* pk) //////////////////////////////////////// function PQCLEAN_FALCON512_CLEAN_crypto_sign_verify ( bytes memory /* uint8_t* */ sig, uint16 siglen, bytes memory /* uint8_t* */ m, uint16 mlen, bytes memory /* uint8_t* */ pk ) public pure returns (int16) { if (siglen < 1 + NONCELEN) // 1 + 40 { return -11; } if (uint8(sig[0]) != (0x30 + 9)) { return -12; } uint ii; uint sourceOffset; uint8[NONCELEN] storage nonce; uint32 sigbuflen = siglen - 1 - NONCELEN; //uint8[sigbuflen] storage sigbuf; uint8[g_SIGBUFLEN] storage sigbuf; int16 retval; sourceOffset = 1; for (ii=0; ii<NONCELEN; ii++) { nonce[ii] = uint8(sig[sourceOffset + ii]); } sourceOffset = 1 + NONCELEN; for (ii=0; ii<sigbuflen; ii++) { sigbuf[ii] = uint8(sig[sourceOffset + ii]); } //fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_crypto_sign_verify() Calling do_verify()\n"); retval = do_verify(nonce, sigbuf, sigbuflen, m, mlen, pk); return retval; } //} // ==== pqclean.c END ===================================================================================================================== // ==== falcon_dataset_from_kestrel.h BEGIN ===================================================================================================================== //contract lib_falcon_dataset_from_kestrel //{ // "Falcon512VerifyTest_Signature.txt" // Size = 658 (0x292) bytes // The 1st byte of the signature (0x39 = 00111001 = 0cc1nnnn) is telling us that... // a) cc is 01 (i.e. Encoding uses the compression algorithm described in Section 3.11.2) // b) nnnn is 1001 (9) uint32 constant g_signatureLen = 658; uint32 constant g_SIGBUFLEN = g_signatureLen - 1 - NONCELEN; uint8[658] g_signature = [ // 0-----1-----2-----3-----4-----5-----6-----7-----8-----9----10-----1-----2-----3-----4-----5-----6-----7-----8-----9----20-----1-----2-----3-----4-----5-----6-----7-----8-----9----30-----1 // SignatureType [1] 0x39, // Nonce [40] 0x01, 0x91, 0xEF, 0x48, 0x48, 0x6E, 0xB9, 0xD9, 0xA6, 0x82, 0x3D, 0x8E, 0x6F, 0xF0, 0xD7, 0xF4, 0xDF, 0x8B, 0xED, 0x13, 0xAF, 0x7F, 0xA5, 0x5A, 0x7E, 0x8D, 0xFA, 0x0D, 0x19, 0x72, 0x58, 0x42, 0xA5, 0x45, 0x1B, 0xCF, 0x4C, 0x06, 0x19, 0x82, // Actual Signature [658 - 1 - 40 = 617] 0xD0, 0x21, 0xC6, 0x3A, 0x7D, 0x66, 0x6C, 0x20, 0x24, 0xFE, 0x57, 0x03, 0x3B, 0x1A, 0x1B, 0xDA, 0x8C, 0x21, 0x79, 0xC5, 0x18, 0xC9, 0x4D, 0x43, 0x49, 0x47, 0xEA, 0xCC, 0x10, 0x9E, 0xFE, 0x79, 0x28, 0x57, 0xFF, 0x64, 0x50, 0xCC, 0x85, 0x3E, 0x8B, 0xB9, 0xD5, 0xD9, 0x51, 0xB3, 0xDD, 0xB1, 0x39, 0x7F, 0xAD, 0xC2, 0x21, 0x07, 0x62, 0xB4, 0x79, 0xE3, 0x86, 0xE6, 0x60, 0xA6, 0x8E, 0xB2, 0xAD, 0x03, 0x4A, 0x58, 0xA3, 0xD0, 0xCC, 0xE2, 0x37, 0x0E, 0xDF, 0x25, 0x7F, 0xF4, 0xF8, 0x1F, 0xE9, 0x7C, 0x9B, 0xB1, 0x0C, 0x1A, 0x96, 0xEE, 0x87, 0xD2, 0x41, 0x4F, 0xDF, 0x4E, 0xA3, 0x9F, 0x9F, 0x7C, 0x06, 0x04, 0xD1, 0xA3, 0xAE, 0xBE, 0x5D, 0x73, 0xA6, 0xA1, 0xF7, 0x22, 0x1A, 0x99, 0xEB, 0x23, 0x89, 0xB9, 0x05, 0xDA, 0x94, 0x76, 0x6C, 0xD2, 0x7A, 0x9A, 0x89, 0xF1, 0x3D, 0x56, 0xB9, 0x7C, 0xDD, 0x34, 0x66, 0x89, 0xCF, 0xC5, 0xB3, 0xBD, 0xBB, 0xDC, 0x51, 0x02, 0xD3, 0xB5, 0xF9, 0x3A, 0x2A, 0x95, 0xBE, 0x40, 0xAF, 0xCA, 0xAC, 0x41, 0x6D, 0x83, 0x13, 0x91, 0x47, 0x4C, 0x22, 0x98, 0xDA, 0x0A, 0x35, 0x9B, 0xC9, 0x58, 0xA5, 0xF2, 0x27, 0xDE, 0x99, 0x1A, 0x33, 0x89, 0x44, 0xD6, 0xEB, 0xE4, 0x96, 0x3F, 0x1A, 0x4B, 0xA5, 0xBB, 0x3D, 0x5C, 0x67, 0x25, 0x26, 0x99, 0x23, 0x29, 0xC8, 0x4C, 0x57, 0x70, 0xC0, 0x3A, 0x5E, 0x43, 0x50, 0x4A, 0x28, 0xFA, 0x86, 0xF3, 0xB9, 0xBD, 0x72, 0x35, 0x4C, 0x0B, 0x19, 0x21, 0xD1, 0xB5, 0x68, 0xE5, 0x21, 0x28, 0x56, 0xD8, 0x43, 0x6F, 0x79, 0xA8, 0xC4, 0x09, 0xE6, 0x31, 0x08, 0x2A, 0x4E, 0x28, 0xB7, 0xCB, 0x99, 0xD8, 0x9C, 0x2A, 0x9A, 0xB3, 0xC1, 0x96, 0xC5, 0x6A, 0x77, 0xE6, 0xD0, 0x57, 0x18, 0x19, 0x6B, 0x31, 0x6D, 0x8E, 0x9B, 0xED, 0xCF, 0xC2, 0x14, 0xE2, 0xA3, 0x3C, 0x02, 0xF0, 0xAF, 0xD8, 0x21, 0xDB, 0xFC, 0xB9, 0x66, 0xC8, 0xBB, 0x8D, 0xDE, 0x01, 0xC8, 0x12, 0xA2, 0x04, 0x5B, 0x6B, 0xC8, 0xDE, 0x76, 0x7F, 0x97, 0xB7, 0x39, 0xDC, 0x8E, 0xD2, 0x62, 0xF4, 0x3D, 0xFC, 0x09, 0x2E, 0x49, 0xF3, 0x4C, 0x77, 0x28, 0x83, 0x98, 0x95, 0xE4, 0x62, 0x06, 0x20, 0xE4, 0xA1, 0x93, 0xE9, 0x4D, 0xBF, 0x2A, 0x9D, 0x43, 0x9E, 0x24, 0x9E, 0x6E, 0xC3, 0x37, 0x7E, 0xD6, 0x73, 0x40, 0x30, 0xAC, 0xD4, 0x3D, 0x13, 0x8B, 0x98, 0x2C, 0x36, 0xDF, 0x81, 0x4A, 0x42, 0x57, 0xF9, 0x71, 0xA5, 0x3A, 0xA5, 0xD9, 0x2A, 0x76, 0x70, 0x91, 0x54, 0x69, 0x01, 0x3E, 0x68, 0x12, 0x4E, 0xDA, 0xE3, 0xFC, 0x11, 0xB4, 0xCA, 0x47, 0x09, 0x38, 0xEE, 0x2F, 0x21, 0x8B, 0xC0, 0xE1, 0x14, 0x68, 0xA6, 0x09, 0x2F, 0x23, 0x3D, 0xE9, 0x14, 0x79, 0x0C, 0x97, 0x2F, 0x77, 0xD9, 0x5F, 0x96, 0x8A, 0xC5, 0xF6, 0xE0, 0x96, 0x8E, 0x0E, 0xFA, 0x8D, 0x62, 0x88, 0x25, 0xF3, 0xFB, 0xAD, 0x22, 0x54, 0xE0, 0x4E, 0x9B, 0xA3, 0x4D, 0xEF, 0xC6, 0x98, 0xB2, 0xE1, 0x9E, 0x96, 0x29, 0x29, 0x0F, 0x4E, 0x56, 0x82, 0x27, 0x05, 0x95, 0x03, 0x5B, 0x07, 0x40, 0x4B, 0x09, 0x1F, 0x53, 0x25, 0x29, 0x3E, 0xD4, 0x02, 0x1C, 0x61, 0x9D, 0x7F, 0x09, 0x14, 0xAC, 0x47, 0x21, 0x9B, 0x9E, 0x5D, 0xF6, 0xFD, 0xA5, 0xAC, 0xBB, 0x39, 0x8A, 0xDB, 0x5C, 0x85, 0x40, 0xDC, 0x33, 0x90, 0xA5, 0x48, 0xD8, 0x2B, 0xE4, 0x2F, 0xAC, 0x8F, 0x6E, 0xF9, 0x96, 0x35, 0x46, 0xBC, 0xF2, 0x78, 0xE6, 0x3F, 0xDD, 0x49, 0xD0, 0xAB, 0xBE, 0x62, 0x20, 0x8E, 0x39, 0x56, 0x46, 0x87, 0x71, 0xDF, 0x4A, 0x50, 0xDD, 0x7A, 0x3A, 0xA1, 0x97, 0xD8, 0x1F, 0x58, 0xC1, 0x44, 0x25, 0xEE, 0x16, 0x6D, 0x29, 0xAE, 0xF3, 0xEB, 0x2C, 0x17, 0x1F, 0xF9, 0xB2, 0x4F, 0x57, 0x5E, 0x0A, 0xE9, 0xA6, 0x52, 0x27, 0xD1, 0xE5, 0x7A, 0xB6, 0xC5, 0xDF, 0x11, 0xA3, 0x69, 0x64, 0x5D, 0xAC, 0x71, 0x7A, 0xB6, 0x71, 0xA4, 0xC1, 0x0A, 0xEF, 0x72, 0x82, 0x41, 0x34, 0xD0, 0xE6, 0x86, 0x76, 0xBB, 0x13, 0x8C, 0xA2, 0x0E, 0xB5, 0xE0, 0x8A, 0x0D, 0x1F, 0x90, 0xEE, 0x48, 0xAF, 0x1C, 0xCE, 0x1F, 0x21, 0xC7, 0x23, 0x94, 0xAC, 0x42, 0x7F, 0x38, 0x2C, 0xED, 0x54, 0x51, 0x83, 0x68, 0x9C, 0xDB, 0x72, 0xCE, 0xC8, 0xEA, 0x30, 0xC7, 0x73, 0x89, 0xA1, 0x62, 0x04, 0x35, 0x62, 0x59, 0xE4, 0xB1, 0x14, 0x2D ]; // "Falcon512VerifyTest_PublicKey.txt" // Size = 897 (0x381) bytes // The 1st byte of the publicKey (0x09 = 00001001 = 0000nnnn) is telling us that... // a) nnnn is 1001 (9) // Ensure that the least significant nybble of pubKey[0] (logn) is in the range 1..10 // 1st byte = 0cc1nnnn, where nnnn = logn // 1st byte = 09, so logn = 9 // Length check: // if (logn <= 1) // return uint16(4) + 1; // else // return (uint16(7) << ((logn) - 2)) + 1; // logn = 9, so we must use the else calculation // 7 = (0000 0000 0000 0111) // logn-2 = 7 // (0000 0000 0000 0111) << 7 = (0000 0011 1000 0000) = 0x0380 // 0x0380 + 1 = 0x0381 = 897 // i.e. Length is good uint32 constant g_pubKeyLen = 897; uint8[897] g_pubKey = [ // 0-----1-----2-----3-----4-----5-----6-----7-----8-----9----10-----1-----2-----3-----4-----5-----6-----7-----8-----9----20-----1-----2-----3-----4-----5-----6-----7-----8-----9----30-----1 0xD8, 0x75, 0x5E, 0x9F, 0x1F, 0xD2, 0x05, 0x64, 0x76, 0x25, 0x85, 0xBA, 0xA5, 0xA4, 0xF1, 0x65, 0xEB, 0xEC, 0x6D, 0xF8, 0x0A, 0xB5, 0x24, 0x8A, 0x22, 0xBB, 0xA9, 0x40, 0xA7, 0x75, 0x4A, 0xBE, 0x53, 0x29, 0xB5, 0xC6, 0x03, 0x45, 0xF3, 0x95, 0xAD, 0x2A, 0x33, 0xAC, 0x10, 0x6E, 0x65, 0xF1, 0x4B, 0x91, 0xD0, 0xDC, 0xA3, 0x08, 0xAE, 0x4C, 0xC6, 0xDB, 0x5F, 0xE6, 0x9E, 0xEE, 0x9F, 0xE4, 0xA3, 0x92, 0xFF, 0x64, 0xF5, 0x28, 0x65, 0x07, 0x0E, 0xB5, 0x58, 0x7E, 0x7F, 0x83, 0xAB, 0x6C, 0x18, 0x7C, 0xC0, 0x58, 0x4B, 0x35, 0x52, 0x92, 0x0A, 0x3D, 0x4B, 0x50, 0xAB, 0x0A, 0x4A, 0x1E, 0x8D, 0x9D, 0xEA, 0x3D, 0x4B, 0x5E, 0xB0, 0x15, 0xA2, 0xF4, 0xAB, 0x59, 0xAE, 0x3D, 0x0A, 0xD2, 0xC0, 0x81, 0xD8, 0xD2, 0x42, 0x8A, 0x83, 0x80, 0x6D, 0xE7, 0x97, 0x3E, 0xC6, 0x59, 0x75, 0xFF, 0x8F, 0xD7, 0x28, 0x7C, 0x64, 0x2B, 0x6A, 0x83, 0x25, 0x02, 0x55, 0xB6, 0x18, 0x38, 0xCB, 0x4D, 0x68, 0xC5, 0x26, 0x00, 0xB8, 0xC5, 0x33, 0x0F, 0xCE, 0x48, 0xAA, 0xEB, 0x80, 0x6D, 0x4F, 0xB9, 0x9A, 0x9A, 0xDD, 0x5E, 0x56, 0x57, 0x74, 0x54, 0xA5, 0xA5, 0xAD, 0x56, 0x99, 0x71, 0x1D, 0xD0, 0x48, 0x54, 0xBF, 0x11, 0x48, 0x47, 0x13, 0xDE, 0xA5, 0xD9, 0xAB, 0xD1, 0x7F, 0x92, 0x14, 0xC3, 0x3C, 0x4F, 0x4D, 0x47, 0xA6, 0x60, 0x0B, 0xC2, 0x41, 0x01, 0x1F, 0x52, 0xE2, 0x9D, 0x98, 0x20, 0xAC, 0x85, 0xAB, 0x70, 0xDF, 0xCC, 0xB1, 0xD0, 0x8C, 0x00, 0x3B, 0x48, 0x9C, 0x08, 0x26, 0xBF, 0x28, 0xCC, 0xEE, 0x71, 0x94, 0x56, 0x37, 0xB7, 0x16, 0x1E, 0x6A, 0x99, 0x58, 0x44, 0x51, 0xBF, 0x83, 0x51, 0xA4, 0x3A, 0x0B, 0x07, 0x55, 0xCE, 0x30, 0x44, 0xF0, 0x84, 0x0B, 0x7A, 0xD0, 0x48, 0x9E, 0x65, 0x72, 0xC8, 0x96, 0x66, 0x64, 0x63, 0xE2, 0xCF, 0xC8, 0xEB, 0xE1, 0x25, 0x8E, 0x3A, 0x96, 0x3A, 0xB1, 0x43, 0x3B, 0x17, 0x38, 0x65, 0x70, 0x5C, 0x15, 0xF0, 0x44, 0xBC, 0xFD, 0xE1, 0xB7, 0x80, 0xD2, 0x9E, 0x42, 0x26, 0x04, 0xA9, 0x08, 0x1D, 0x23, 0x49, 0xF6, 0xD6, 0xB4, 0x06, 0x71, 0xB7, 0xC6, 0xAE, 0x77, 0xF4, 0x4C, 0x16, 0xA2, 0x24, 0x12, 0xE9, 0xE3, 0x2C, 0xB1, 0x16, 0x36, 0x3D, 0x99, 0xCA, 0x4D, 0x2C, 0x3A, 0xCE, 0x67, 0x30, 0xFD, 0x45, 0xFC, 0x66, 0x12, 0xD3, 0x89, 0xED, 0xCD, 0x1C, 0x9B, 0x22, 0x01, 0xBA, 0x32, 0xA4, 0x70, 0x5F, 0xAC, 0x61, 0x00, 0x5E, 0x18, 0x4B, 0x89, 0xA4, 0xC9, 0x09, 0x83, 0xAC, 0xD7, 0xAF, 0xEE, 0x69, 0x4A, 0xC9, 0xD9, 0x04, 0x47, 0x3E, 0xB5, 0x12, 0xEC, 0x2D, 0x48, 0x75, 0xC1, 0xC9, 0x54, 0xB7, 0x91, 0x50, 0x6F, 0x02, 0xC9, 0xE6, 0x5F, 0x5D, 0x04, 0x97, 0x6E, 0xA4, 0xE8, 0x1D, 0x22, 0xD4, 0x88, 0x4E, 0xB1, 0xC4, 0x7E, 0xEB, 0x1A, 0x7E, 0xE1, 0x09, 0xE1, 0x2E, 0x61, 0xCE, 0x0E, 0xE4, 0xDF, 0xA8, 0x8F, 0xDA, 0xCB, 0x78, 0xED, 0x61, 0xB0, 0xA3, 0x27, 0xC2, 0x06, 0x9D, 0x8C, 0xD3, 0x3D, 0x18, 0x4E, 0x68, 0xA6, 0x0C, 0x22, 0xF6, 0x80, 0x4F, 0xAC, 0xEC, 0xA9, 0x68, 0xCF, 0x5C, 0x1C, 0x27, 0x6C, 0x7D, 0x16, 0x38, 0x6F, 0x38, 0xBB, 0x82, 0xD5, 0xEA, 0x1E, 0x11, 0xD8, 0x01, 0xF5, 0xEF, 0x33, 0xD3, 0xA3, 0xB0, 0x17, 0x1D, 0xC8, 0x70, 0x74, 0x1C, 0xE8, 0x37, 0x3C, 0x77, 0x9A, 0xE8, 0x93, 0x52, 0x11, 0x34, 0x8C, 0x43, 0x62, 0x85, 0x70, 0x36, 0x81, 0xF1, 0xE6, 0xB0, 0xAD, 0xC0, 0x5C, 0x35, 0xC5, 0x61, 0x96, 0xC2, 0x46, 0x73, 0x1E, 0xE2, 0xA4, 0xA9, 0x98, 0xEF, 0x91, 0x8A, 0x16, 0x50, 0x23, 0xA7, 0x6D, 0x32, 0x4C, 0x58, 0x41, 0x9C, 0xD9, 0xE7, 0x6E, 0xBC, 0xA0, 0xE1, 0x38, 0x23, 0xD9, 0x0B, 0x2E, 0xBC, 0x64, 0x17, 0x17, 0xB4, 0x04, 0xE2, 0xEE, 0x29, 0x37, 0xD4, 0x8B, 0x38, 0x44, 0x1E, 0x88, 0xF1, 0x08, 0x6C, 0x15, 0xC9, 0x5D, 0xE8, 0xA4, 0x86, 0x32, 0xBE, 0xE5, 0xFB, 0x56, 0xF9, 0x9F, 0x07, 0xAC, 0x31, 0x03, 0x73, 0x23, 0x00, 0x03, 0x17, 0xC2, 0x91, 0xE2, 0xEA, 0xCE, 0x78, 0x65, 0xEC, 0xE2, 0x35, 0x48, 0xE8, 0x04, 0x67, 0x92, 0x41, 0xF1, 0x36, 0x67, 0x48, 0xB1, 0x65, 0x6C, 0xD5, 0x8C, 0x28, 0xB8, 0x6D, 0x5E, 0x08, 0xE2, 0x69, 0xD0, 0xE3, 0xA6, 0x68, 0xA8, 0x34, 0xF4, 0x17, 0x8A, 0x18, 0x8D, 0xD6, 0x33, 0x84, 0x04, 0x27, 0x73, 0xFA, 0xC1, 0x0B, 0x3D, 0x96, 0xF5, 0x33, 0xEC, 0xAB, 0xE3, 0xA8, 0xA2, 0x7E, 0x09, 0x1D, 0x58, 0x46, 0xD6, 0xEA, 0xD8, 0xAC, 0x92, 0x41, 0x43, 0x72, 0x40, 0xAD, 0x4F, 0x7D, 0x27, 0x4B, 0x78, 0x40, 0x34, 0x02, 0x21, 0x0A, 0xD0, 0x42, 0xDD, 0xF7, 0x3D, 0x59, 0xE0, 0x2A, 0xBF, 0x65, 0x7A, 0xA4, 0x1E, 0x10, 0x14, 0x55, 0xDF, 0x63, 0x8D, 0x44, 0xC1, 0x81, 0xE4, 0xCA, 0x21, 0x9F, 0x2C, 0x66, 0x79, 0x08, 0x8F, 0xF1, 0x1A, 0xF4, 0x39, 0x11, 0x5D, 0x8E, 0xF3, 0x8F, 0x36, 0x14, 0xB9, 0x57, 0xE1, 0xEB, 0xB9, 0xCC, 0x2E, 0x6B, 0xEE, 0x0C, 0x06, 0x64, 0xDA, 0x7B, 0xA3, 0xF1, 0x26, 0x84, 0x04, 0xA5, 0xBA, 0xC8, 0xED, 0x45, 0x85, 0x48, 0x81, 0x97, 0x23, 0x82, 0x90, 0x88, 0x61, 0xCC, 0x7F, 0x14, 0xF5, 0xD0, 0x3B, 0x11, 0x22, 0x73, 0x91, 0x78, 0x54, 0x61, 0x75, 0x90, 0xAA, 0xD7, 0x0E, 0xEE, 0xDF, 0x39, 0x8C, 0xB2, 0x06, 0xFF, 0x5C, 0x7F, 0x7A, 0x9C, 0x53, 0x90, 0xDF, 0xA2, 0x7E, 0x14, 0xB1, 0x14, 0x85, 0x18, 0x83, 0x3B, 0x33, 0x75, 0xCD, 0xFA, 0xF5, 0xA7, 0x36, 0x80, 0xCD, 0xD7, 0xD0, 0xEA, 0x5F, 0x66, 0x46, 0x72, 0xFE, 0x91, 0xAE, 0x67, 0x00, 0x03, 0x2A, 0x3E, 0xE2, 0x1A, 0xEB, 0x3A, 0xB7, 0xB6, 0xA0, 0xF6, 0x6B, 0x0F, 0x65, 0x59, 0x7A, 0x7F, 0xB6, 0xF5, 0xC1, 0xA9, 0xB1, 0x45, 0x9D, 0x48, 0x88, 0x5D, 0xB3, 0x73, 0x4A, 0xBE, 0xC9, 0x91, 0x8C, 0x0F, 0x3A, 0x81, 0x35, 0xBB, 0xB2, 0x27, 0x99, 0x84, 0xA0, 0x54, 0x11, 0x5E, 0x9C, 0x12, 0xA8, 0xF1, 0x0C, 0xA2, 0x5B, 0x93, 0xBE, 0x8A, 0x3A, 0xCF, 0xB9, 0x4D, 0xC6, 0xA9, 0x0D, 0x4D, 0xA0, 0xE0, 0xA7, 0xAD, 0xA8 ]; // "Falcon512VerifyTest_Message.txt" // Size = 100 (0x64) bytes // 100 bytes of random data uint32 constant g_messageLen = 100; uint8[100] g_message = [ // 0-----1-----2-----3-----4-----5-----6-----7-----8-----9----10-----1-----2-----3-----4-----5-----6-----7-----8-----9----20-----1-----2-----3-----4-----5-----6-----7-----8-----9----30-----1 0x36, 0xEA, 0x37, 0x8A, 0x89, 0x29, 0x4F, 0x83, 0x9D, 0xC9, 0xBC, 0xD9, 0xA8, 0x25, 0x1F, 0x92, 0xCF, 0xD3, 0x9A, 0xAC, 0xC1, 0xE2, 0x28, 0xF4, 0x44, 0x42, 0xE9, 0x5B, 0x3C, 0x59, 0xEF, 0x90, 0x46, 0x13, 0xEC, 0xE9, 0xD3, 0x12, 0x02, 0x8B, 0x07, 0xA3, 0xCB, 0x26, 0xB3, 0xC9, 0x84, 0x4D, 0xCD, 0xB2, 0x69, 0x92, 0x99, 0xD7, 0xD4, 0x7F, 0xD6, 0x3F, 0x78, 0x89, 0xD6, 0xC5, 0xCE, 0x34, 0x62, 0x6B, 0x58, 0x3A ]; //} // ==== falcon_dataset_from_kestrel.h END ===================================================================================================================== // ==== test_sig.c BEGIN ===================================================================================================================== //import "lib_falcon_pqclean.sol"; //import "lib_falcon_dataset_from_kestrel.sol" //contract con_falcon_test_sig //{ bool constant TEST_HAPPY_PATH = true; bool constant TEST_UNHAPPY_PATH = true; int8 constant EXIT_SUCCESS = 0; int8 constant EXIT_FAILURE = -1; // OQS_STATUS; int8 constant OQS_ERROR = -1; int8 constant OQS_SUCCESS = 0; int8 constant OQS_EXTERNAL_LIB_ERROR_OPENSSL = 50; //#ifdef TEST_UNHAPPY_PATH function CorruptSomeBits(bytes memory /* unsigned char **/ pData, uint16 cbData) private pure { // TODO - Any corruption will do //if (cbData > 0) { pData[ 0] = ~(pData[ 0]); } //if (cbData > 10) { pData[ 10] = ~(pData[ 10]); } //if (cbData > 100) { pData[100] = ~(pData[100]); } } //#endif //////////////////////////////////////// // //////////////////////////////////////// function main() public pure returns (int16) { uint8[] storage public_key; uint32 public_key_len = 0; uint8[] storage message; uint32 message_len = 0; uint8[] storage signature; uint32 signature_len; int16 rc; int8 ret = EXIT_FAILURE; //printf("*** ================================================================================\n"); //printf("*** Sample computation for signature Falcon-512\n"); //printf("*** ================================================================================\n"); do { public_key = g_pubKey; public_key_len = g_pubKeyLen; message = g_message; message_len = g_messageLen; signature = g_signature; signature_len = g_signatureLen; if (public_key_len != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES) { //fprintf(stderr, "ERROR: Length of Public key (%lu) not as expected (%u)\n", public_key_len, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES); ret = EXIT_FAILURE; break; } if (TEST_HAPPY_PATH) { //fprintf(stdout, "-------------------------------------------------------------------------------------\n"); //fprintf(stdout, "*** Calling PQCLEAN_FALCON512_CLEAN_crypto_sign_verify()\n"); rc = PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(signature, signature_len, message, message_len, public_key); if (rc != OQS_SUCCESS) { //fprintf(stderr, "ERROR: PQCLEAN_FALCON512_CLEAN_crypto_sign_verify failed\n"); ret = EXIT_FAILURE; break; } } if (TEST_UNHAPPY_PATH) { //fprintf(stdout, "*** -------------------------------------------------------------------------------------\n"); //fprintf(stdout, "*** Modify the signature to invalidate it\n"); CorruptSomeBits(signature, signature_len); // Modify the signature in order to invalidate it and force a failure //fprintf(stdout, "*** Calling PQCLEAN_FALCON512_CLEAN_crypto_sign_verify()\n"); rc = PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(signature, signature_len, message, message_len, public_key); if (rc != OQS_ERROR) { //fprintf(stderr, "ERROR: PQCLEAN_FALCON512_CLEAN_crypto_sign_verify should have failed!\n"); ret = EXIT_FAILURE; break; } } //fprintf(stdout, "*** All tests pass OK\n"); ret = EXIT_SUCCESS; break; } while (0); //fprintf(stdout, "*** Cleanup...\n"); return ret; } } // ==== test_sig.c END =====================================================================================================================
Ensure that the least significant nybble of pubKey[0] (logn) is in the range 1..10 1st byte = 0cc1nnnn, where nnnn = logn 1st byte = 09, so logn = 9 Length check: if (logn <= 1) return uint16(4) + 1; else return (uint16(7) << ((logn) - 2)) + 1; logn = 9, so we must use the else calculation 7 = (0000 0000 0000 0111) logn-2 = 7 (0000 0000 0000 0111) << 7 = (0000 0011 1000 0000) = 0x0380 0x0380 + 1 = 0x0381 = 897 i.e. Length is good
uint32 constant g_pubKeyLen = 897;
1,775,457
[ 1, 12512, 716, 326, 4520, 14177, 15308, 70, 7119, 434, 18659, 63, 20, 65, 261, 1330, 82, 13, 353, 316, 326, 1048, 404, 838, 2163, 377, 404, 334, 1160, 273, 374, 952, 21, 9074, 9074, 16, 1625, 7761, 9074, 273, 613, 82, 377, 404, 334, 1160, 273, 21058, 16, 1427, 613, 82, 273, 2468, 11311, 866, 30, 377, 309, 261, 1330, 82, 1648, 404, 13, 3639, 327, 2254, 2313, 12, 24, 13, 397, 404, 31, 377, 469, 3639, 327, 261, 11890, 2313, 12, 27, 13, 2296, 14015, 1330, 82, 13, 300, 576, 3719, 397, 404, 31, 377, 613, 82, 273, 2468, 16, 1427, 732, 1297, 999, 326, 469, 11096, 377, 2371, 273, 261, 2787, 374, 3784, 374, 3784, 374, 20227, 13, 377, 613, 82, 17, 22, 273, 2371, 377, 261, 2787, 374, 3784, 374, 3784, 374, 20227, 13, 2296, 2371, 273, 261, 2787, 374, 1611, 21, 4336, 374, 3784, 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, 2254, 1578, 5381, 314, 67, 10174, 653, 2891, 273, 1725, 10580, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5d880cfc028bFDD083B0D3dAf57286141596D4E9/sources/contracts/IvstSale.sol
* @notice Add payment token/
function addPaymentToken(address _token, address _feed, uint8 _decimal) external onlyOwner { require(!isPaymentToken[_token], "already added"); require(_feed != address(0), "invalid feed address"); require(_decimal > 0, "no zero decimal"); (, int256 price, , , ) = AggregatorV3Interface(_feed).latestRoundData(); require(price > 0, "invalid price feed"); isPaymentToken[_token] = true; allPaymentTokens.push(_token); priceFeed[_token] = _feed; paymentTokenDecimal[_token] = _decimal; emit PaymentTokenAdded(_token, _feed, _decimal); }
17,165,262
[ 1, 986, 5184, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 6032, 1345, 12, 2867, 389, 2316, 16, 1758, 389, 7848, 16, 2254, 28, 389, 12586, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 291, 6032, 1345, 63, 67, 2316, 6487, 315, 17583, 3096, 8863, 203, 3639, 2583, 24899, 7848, 480, 1758, 12, 20, 3631, 315, 5387, 4746, 1758, 8863, 203, 3639, 2583, 24899, 12586, 405, 374, 16, 315, 2135, 3634, 6970, 8863, 203, 203, 3639, 261, 16, 509, 5034, 6205, 16, 269, 269, 262, 273, 10594, 639, 58, 23, 1358, 24899, 7848, 2934, 13550, 11066, 751, 5621, 203, 3639, 2583, 12, 8694, 405, 374, 16, 315, 5387, 6205, 4746, 8863, 203, 203, 3639, 353, 6032, 1345, 63, 67, 2316, 65, 273, 638, 31, 203, 3639, 777, 6032, 5157, 18, 6206, 24899, 2316, 1769, 203, 3639, 6205, 8141, 63, 67, 2316, 65, 273, 389, 7848, 31, 203, 3639, 5184, 1345, 5749, 63, 67, 2316, 65, 273, 389, 12586, 31, 203, 203, 3639, 3626, 12022, 1345, 8602, 24899, 2316, 16, 389, 7848, 16, 389, 12586, 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 ]
./full_match/80001/0x14e39aDc79A7610c685143c4cd891F94dB3B40cD/sources/@aragon/osx/framework/plugin/repo/PluginRepo.sol
@notice Thrown if a release number is zero.
error ReleaseZeroNotAllowed();
5,569,450
[ 1, 29591, 309, 279, 3992, 1300, 353, 3634, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 555, 10819, 7170, 19354, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-18 */ // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/runtz-v5.sol // Wolfpack Labs LLC // Authors: Jimmyisabot, Charmer pragma solidity 0.8.12; contract Hungry_Runtz is ERC721Enumerable, Ownable, ReentrancyGuard { using Strings for uint256; struct SaleState { /// The starting mint (supply) index for the sale. uint32 startSupply; /// The number of mints allowed in this sale series. uint32 seriesSize; /// The number of tokens minted in this series. This is reset when the series is reset or rolled. uint32 seriesSupply; /// The lifetime total supply for this sale (never resets). uint32 totalSupply; /// The limit of tokens to be minted in a single transaction. uint8 maxMint; /// The current index of the hundreds unit being minted. uint16 hundreds; /// The offset of the end of the available (and pre-shuffled) list of remaining ID's for the current hundreds index. uint8 offset; /// If true, this sale is currently paused. bool paused; /// If true, reward minting is paused for this sale. bool wlPaused; /// A shuffled list of IDs for the current block of a hundred tokens being minted. uint8[100] list; } struct AppState { uint128 cost; uint128 count; uint256 nonce; } SaleState _free = SaleState( 0, 30000, 0, 0, 20, 0, 99, true, false, // prettier-ignore [100, 99, 9, 84, 45, 23, 86, 17, 36, 64, 55, 29, 79, 58, 27, 25, 95, 3, 66, 40, 82, 87, 88, 42, 35, 12, 15, 1, 96, 89, 73, 6, 61, 57, 43, 56, 4, 90, 28, 91, 72, 68, 44, 38, 77, 65, 2, 71, 75, 94, 76, 7, 16, 34, 83, 98, 10, 33, 63, 62, 78, 49, 92, 24, 54, 8, 30, 52, 74, 21, 11, 51, 5, 70, 32, 37, 67, 13, 69, 53, 50, 41, 14, 22, 31, 85, 46, 80, 26, 93, 48, 47, 39, 97, 59, 20, 19, 81, 60, 18] ); SaleState _paid = SaleState( 50000, 10000, 0, 0, 20, 0, 99, true, false, // prettier-ignore [64, 26, 33, 81, 16, 41, 82, 55, 95, 2, 18, 20, 5, 84, 93, 21, 53, 94, 96, 73, 34, 11, 78, 98, 51, 30, 17, 68, 14, 92, 86, 75, 58, 31, 69, 36, 27, 4, 44, 63, 42, 35, 7, 47, 37, 65, 87, 100, 74, 61, 28, 24, 49, 13, 54, 12, 8, 29, 80, 83, 38, 43, 70, 85, 66, 45, 10, 22, 46, 77, 56, 76, 48, 71, 60, 89, 15, 97, 40, 67, 39, 52, 91, 79, 25, 1, 6, 62, 32, 19, 59, 23, 9, 3, 90, 57, 72, 99, 88, 50] ); AppState _state = AppState(0.005 ether, 0, uint256(blockhash(block.number)) ^ uint256(block.timestamp)); string public baseURI; string public baseExtension = ".json"; address[] freeWL; address[] paidWL; event ExternalContractFailure(address extContract, bytes error); constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} function freeWLMint(uint256 mintAmount) external payable nonReentrant isHolder(freeWL) { require(!_free.wlPaused, "wl minting is paused"); require(mintAmount <= _free.maxMint, "sale: exceeded max mint amount"); require(_free.seriesSupply + mintAmount <= _free.seriesSize, "sale: not enough supply left"); _doMint(mintAmount, _free); } function paidWLMint(uint256 mintAmount) external payable nonReentrant isHolder(paidWL) { require(!_paid.wlPaused, "wl minting is paused"); require(mintAmount <= _paid.maxMint, "sale: exceeded max mint amount"); require(_paid.seriesSupply + mintAmount <= _paid.seriesSize, "sale: not enough supply left"); require(msg.value >= _state.cost * mintAmount); _doMint(mintAmount, _paid); } function paidMint(uint256 _mintAmount) external payable nonReentrant withValidMint(_paid, _mintAmount) { require(msg.value >= _state.cost * _mintAmount); _doMint(_mintAmount, _paid); } function freeMint(uint256 mintAmount) external payable nonReentrant withValidMint(_free, mintAmount) { _doMint(mintAmount, _free); } function _doMint(uint256 _mintAmount, SaleState storage sale) internal { // uint8[100] storage list = sale.list; uint8 offset = sale.offset; uint16 hundreds = sale.hundreds; uint256 nonce = _state.nonce; for (uint256 i = 1; i <= _mintAmount; i++) { // Get a random number and swap it to the end of the list. uint256 rand = nonce % (offset + 1); uint8 nextId = sale.list[rand]; sale.list[rand] = sale.list[offset]; sale.list[offset] = nextId; // Make sure we get the current token id before rolling the hundreds and resetting the id offset. uint256 id = sale.startSupply + (hundreds * 100) + nextId; // Check to see if we have used the last id in the list for this block of one hundred. if (offset == 0) { // Reset the id offset and move to the next block of one hundred. offset = 99; hundreds++; } else { // Mark one more id in the list as used. offset--; } // We can finally mint a single token! That was a lot of effort, but I think we can all agree it is worth it! _safeMint(msg.sender, id); // Update the nonce to take into account the current mint count. nonce = nextNonce(nonce, i); } // Update the contract storage with the new state. This is done once here at the end of the transaction so that we // can reduce the number of writes to storage. sale.seriesSupply += uint32(_mintAmount); sale.totalSupply += uint32(_mintAmount); _state.count += uint32(_mintAmount); sale.hundreds = hundreds; sale.offset = offset; _state.nonce = nonce; } modifier isHolder(address[] memory wl) { bool holder = false; bytes4 iid = type(IERC721).interfaceId; for (uint256 i = 0; i < wl.length && !holder; i++) { ERC721 ext = ERC721(wl[i]); if (ext.supportsInterface(iid)) { try ext.balanceOf(msg.sender) returns (uint256 count) { holder = count > 0; } catch (bytes memory error) { // Ignore the error as it doesn't give access to anything. emit ExternalContractFailure(address(ext), error); } } } require(holder, "sender is not an owner of provided token"); _; } modifier withValidMint(SaleState memory sale, uint256 mintAmount) { require(!sale.paused, "sale: not active"); require(mintAmount <= sale.maxMint, "sale: exceeded max mint amount"); require(sale.seriesSupply + mintAmount <= sale.seriesSize, "sale: not enough supply left"); _; } function nextNonce(uint256 previousNonce, uint256 counter) internal view returns (uint256 nonce) { bytes memory input = abi.encodePacked( previousNonce ^ counter, block.timestamp, block.difficulty, block.gaslimit, msg.sender ); nonce = uint256(keccak256(input)); } function randMod(uint256 modulus) internal view returns (uint256 rand) { rand = _state.nonce % modulus; } function walletOfOwner(address owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); } return tokenIds; } // Free Mint Functions function setFreeMaxMint(uint8 freeMaxMint) external onlyOwner { _free.maxMint = freeMaxMint; } function setFreeStart(uint32 supply) external onlyOwner { _free.startSupply = supply; } function setFreeOffset(uint8 idx) external onlyOwner { _free.offset = idx; } function setFreeHundredsIndex(uint16 idx) external onlyOwner { _free.hundreds = idx; } function freeMintPause(bool paused) external onlyOwner { _free.paused = paused; } function setFreeSeriesSupply(uint32 supply) external onlyOwner { _free.seriesSupply = supply; } function setFreeSeriesSize(uint32 freeSize) external onlyOwner { _free.seriesSize = freeSize; } function setFreeWL(address[] calldata contracts) external onlyOwner { for (uint256 i = 0; i < contracts.length; i++) { freeWL.push(contracts[i]); } } function pauseFreeWL(bool paused) external onlyOwner { _free.wlPaused = paused; } function getFreeState() external view onlyOwner returns (SaleState memory _freeState) { _freeState = _free; return _freeState; } function getPaidState() external view onlyOwner returns (SaleState memory) { return _paid; } // Paid Mint Functions function setPaidCost(uint128 cost) external onlyOwner { _state.cost = cost; } function setPaidMaxMint(uint8 paidMaxMint) external onlyOwner { _paid.maxMint = paidMaxMint; } function setPaidStart(uint32 supply) external onlyOwner { _paid.startSupply = supply; } function setPaidOffset(uint8 idx) external onlyOwner { _paid.offset = idx; } function setPaidHundredsIndex(uint16 idx) external onlyOwner { _paid.hundreds = idx; } function paidMintPause(bool state) external onlyOwner { _paid.paused = state; } function setPaidSeriesSupply(uint32 supply) external onlyOwner { _paid.seriesSupply = supply; } function setPaidSeriesSize(uint32 size) external onlyOwner { _paid.seriesSize = size; } function setPaidWL(address[] calldata contracts) external onlyOwner { for (uint256 i = 0; i < contracts.length; i++) { paidWL.push(contracts[i]); } } function pausePaidWL(bool paused) external onlyOwner { _paid.wlPaused = paused; } // Contract-Wide Functions function _baseURI() internal view override returns (string memory) { return baseURI; } function setBaseURI(string memory uri) external onlyOwner { baseURI = uri; } function setBaseExtension(string memory ext) external onlyOwner { baseExtension = ext; } function burnToken(uint256 tokenId) public onlyOwner { require(_isApprovedOrOwner(msg.sender, tokenId)); _burn(tokenId); } function withdraw() public onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
Update the nonce to take into account the current mint count.
nonce = nextNonce(nonce, i);
15,208,848
[ 1, 1891, 326, 7448, 358, 4862, 1368, 2236, 326, 783, 312, 474, 1056, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 7448, 273, 1024, 13611, 12, 12824, 16, 277, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x90e9C5D875a7dE914ABE2bc56Ff149d6537B12C5/sources/MoonOrDust.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("MoonOrDust", "MoD") { 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 = 15; uint256 _buyLiquidityFee = 5; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 15; uint256 _sellLiquidityFee = 5; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
9,243,492
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 16727, 265, 1162, 40, 641, 3113, 315, 16727, 40, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 4711, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 1381, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 2 ]
//Address: 0x6816184f231aa6af7f959d99ec0ace5731ab33f0 //Contract name: RocketStorage //Balance: 0 Ether //Verification Date: 6/14/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.19; // File: contracts/storage/RocketStorage.sol /// @title The primary persistent storage for Rocket Pool /// @author David Rugendyke contract RocketStorage { /**** Storage Types *******/ mapping(bytes32 => uint256) private uIntStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bytes) private bytesStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => int256) private intStorage; /*** Modifiers ************/ /// @dev Only allow access from the latest version of a contract in the Rocket Pool network after deployment modifier onlyLatestRocketNetworkContract() { // The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled if (boolStorage[keccak256("contract.storage.initialised")] == true) { // Make sure the access is permitted to only contracts in our Dapp require(addressStorage[keccak256("contract.address", msg.sender)] != 0x0); } _; } /// @dev constructor constructor() public { // Set the main owner upon deployment boolStorage[keccak256("access.role", "owner", msg.sender)] = true; } /**** Get Methods ***********/ /// @param _key The key for the record function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /// @param _key The key for the record function getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } /// @param _key The key for the record function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } /// @param _key The key for the record function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } /// @param _key The key for the record function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /// @param _key The key for the record function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /**** Set Methods ***********/ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyLatestRocketNetworkContract external { addressStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyLatestRocketNetworkContract external { uIntStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyLatestRocketNetworkContract external { stringStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyLatestRocketNetworkContract external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyLatestRocketNetworkContract external { boolStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyLatestRocketNetworkContract external { intStorage[_key] = _value; } /**** Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyLatestRocketNetworkContract external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyLatestRocketNetworkContract external { delete uIntStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyLatestRocketNetworkContract external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyLatestRocketNetworkContract external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyLatestRocketNetworkContract external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyLatestRocketNetworkContract external { delete intStorage[_key]; } /**** Hash Helpers **************/ function kcck256str(string _key1) external pure returns (bytes32) { return keccak256(_key1); } function kcck256strstr(string _key1, string _key2) external pure returns (bytes32) { return keccak256(_key1, _key2); } function kcck256stradd(string _key1, address _key2) external pure returns (bytes32) { return keccak256(_key1, _key2); } function kcck256straddadd(string _key1, address _key2, address _key3) external pure returns (bytes32) { return keccak256(_key1, _key2, _key3); } }
@param _key The key for the record
function setBytes(bytes32 _key, bytes _value) onlyLatestRocketNetworkContract external { bytesStorage[_key] = _value; }
12,732,865
[ 1, 67, 856, 1021, 498, 364, 326, 1409, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 2160, 12, 3890, 1578, 389, 856, 16, 1731, 389, 1132, 13, 1338, 18650, 54, 1861, 3906, 8924, 3903, 288, 203, 3639, 1731, 3245, 63, 67, 856, 65, 273, 389, 1132, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.11; // ---------------------------------------------------------------------------- // forgivenet 1st phase contract // Request forgiveness and receive an FRGVN token in return // More info @ forgivenet.co.uk // // // (c) Nandi Niramisa & Co Limited 2019. The MIT Licence. https://opensource.org/licenses/MIT // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address _from, address _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract ERC20TokenInterface { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract RequestForForgiveness is Owned { ERC20TokenInterface private token; // receiving account address payable private receivingAccount; // Owner adds receiving account for accounting purposes function addEthReceivingAccount(address addr) public onlyOwner { require(addr != address(0)); receivingAccount = address(uint160(addr)); } // Owner adds ForgivenetToken address function addToken(address ercTokenAddress) public onlyOwner { require(ercTokenAddress != address(0)); token = ERC20TokenInterface(ercTokenAddress); } // Owner deposits token into the contract function depositToken(uint256 amount) public onlyOwner { token = ERC20TokenInterface(token); require(token.transferFrom(msg.sender, address(this), amount) == true); } // A minimum value for a request for forgiveness transaction may disincentivize bad behaviour uint private disincentive; function setDisincentiveInWei(uint number) public onlyOwner { disincentive = number; } function getDisincentive() public view returns (uint) { return disincentive; } // Make Ether payment into receiving account and call withdrawToken with the request function requestForgiveness(string memory forgiveness_request) public payable { uint256 length = bytes(forgiveness_request).length; require(length > 500 && length < 2000); string memory requestStr = forgiveness_request; require(msg.sender != address(0)); require(msg.value > disincentive); receivingAccount.transfer(msg.value); withdrawToken(msg.sender, msg.value, requestStr); } // Send 1 FRGVN token to recipient function withdrawToken(address recipient, uint256 amount, string memory requestString) internal { // placeholder variable for request string memory data = requestString; require(recipient != address(0)); require(bytes(data).length > 0); token = ERC20TokenInterface(token); require(token.transfer(recipient, 1) == true); emit RequestMade(recipient, data, amount, now); } // events event RequestMade(address indexed from, string data, uint256 donation, uint256 timestamp); }
Make Ether payment into receiving account and call withdrawToken with the request
function requestForgiveness(string memory forgiveness_request) public payable { uint256 length = bytes(forgiveness_request).length; require(length > 500 && length < 2000); string memory requestStr = forgiveness_request; require(msg.sender != address(0)); require(msg.value > disincentive); receivingAccount.transfer(msg.value); withdrawToken(msg.sender, msg.value, requestStr); }
12,736,126
[ 1, 6464, 512, 1136, 5184, 1368, 15847, 2236, 471, 745, 598, 9446, 1345, 598, 326, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 590, 1290, 10822, 403, 12, 1080, 3778, 364, 10822, 403, 67, 2293, 13, 1071, 8843, 429, 288, 203, 540, 203, 3639, 2254, 5034, 769, 273, 1731, 12, 1884, 10822, 403, 67, 2293, 2934, 2469, 31, 203, 3639, 2583, 12, 2469, 405, 6604, 597, 769, 411, 16291, 1769, 203, 3639, 533, 3778, 590, 1585, 273, 364, 10822, 403, 67, 2293, 31, 203, 21281, 3639, 2583, 12, 3576, 18, 15330, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 1015, 267, 2998, 688, 1769, 203, 3639, 15847, 3032, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 3639, 598, 9446, 1345, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 590, 1585, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; import'./IERC20.sol'; import './SafeMath.sol'; contract WinikToken is IERC20 { using SafeMath for uint256; uint public _totalsupply = 0; string public constant symbol = "WINIK2"; string public constant name = "Winik Token2"; uint8 public constant decimals = 18; uint256 public constant MaxSupply = 1000000; // 1 ether = 500 WINIK uint256 public constant RATE = 500; address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function() payable { createTokens(); } function WinikToken() { owner = msg.sender; } function createTokens() payable { require(msg.value > 0); require(_totalsupply < MaxSupply.sub(tokens)); uint256 tokens = msg.value.mul(RATE); balances[msg.sender] = balances[msg.sender].add(tokens); _totalsupply = _totalsupply.add(tokens); owner.transfer(msg.value); } function totalSupply() constant returns (uint256 totalSupply) { return _totalsupply; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success) { require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require( allowed[_from][msg.sender] >= _value && balances[_from] > _value && _value > 0 ); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool 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]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
1 ether = 500 WINIK
contract WinikToken is IERC20 { using SafeMath for uint256; uint public _totalsupply = 0; string public constant symbol = "WINIK2"; string public constant name = "Winik Token2"; uint8 public constant decimals = 18; uint256 public constant MaxSupply = 1000000; uint256 public constant RATE = 500; address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function() payable { createTokens(); } function WinikToken() { owner = msg.sender; } function createTokens() payable { require(msg.value > 0); require(_totalsupply < MaxSupply.sub(tokens)); uint256 tokens = msg.value.mul(RATE); balances[msg.sender] = balances[msg.sender].add(tokens); _totalsupply = _totalsupply.add(tokens); owner.transfer(msg.value); } function totalSupply() constant returns (uint256 totalSupply) { return _totalsupply; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success) { require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require( allowed[_from][msg.sender] >= _value && balances[_from] > _value && _value > 0 ); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool 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]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
12,910,800
[ 1, 21, 225, 2437, 273, 6604, 678, 12772, 47, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 21628, 1766, 1345, 353, 467, 654, 39, 3462, 288, 203, 202, 9940, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 202, 11890, 1071, 389, 3307, 1031, 416, 1283, 273, 374, 31, 203, 203, 202, 1080, 1071, 5381, 3273, 273, 315, 59, 12772, 47, 22, 14432, 203, 202, 1080, 1071, 5381, 508, 273, 315, 18049, 1766, 3155, 22, 14432, 203, 202, 11890, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 202, 11890, 5034, 1071, 5381, 4238, 3088, 1283, 273, 15088, 31, 203, 203, 202, 11890, 5034, 1071, 5381, 534, 1777, 273, 6604, 31, 203, 203, 202, 2867, 1071, 3410, 31, 203, 202, 6770, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 202, 6770, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 203, 202, 915, 1435, 8843, 429, 288, 203, 202, 202, 2640, 5157, 5621, 7010, 202, 97, 203, 203, 202, 915, 21628, 1766, 1345, 1435, 288, 203, 202, 202, 8443, 273, 1234, 18, 15330, 31, 203, 202, 97, 203, 203, 202, 915, 752, 5157, 1435, 8843, 429, 288, 203, 202, 202, 6528, 12, 3576, 18, 1132, 405, 374, 1769, 203, 202, 202, 6528, 24899, 3307, 1031, 416, 1283, 411, 4238, 3088, 1283, 18, 1717, 12, 7860, 10019, 203, 202, 202, 11890, 5034, 2430, 273, 1234, 18, 1132, 18, 16411, 12, 24062, 1769, 203, 202, 202, 70, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1289, 12, 7860, 1769, 203, 202, 202, 67, 3307, 1031, 416, 1283, 273, 389, 3307, 1031, 416, 2 ]
./full_match/43114/0xCe039E89B062F89Cd2c2486BC4D64c37b39a1177/sources/patch.sol
Sync up reserves of uniswap liquidity pool Get reserves of uniswap liquidity pool All Oracle prices are priced with 18 decimals against USD Get LP token supply This calculation should be overflow-resistant even for tokens with very high or very low prices, as the dollar value of each reserve should lie in a fairly controlled range regardless of the token prices.
function seek() internal returns (uint128 quote) { UniswapV2PairLike(src).sync(); (uint112 r0, uint112 r1,) = UniswapV2PairLike(src).getReserves(); require(r0 > 0 && r1 > 0, "UNIV2LPOracle/invalid-reserves"); require(p0 != 0, "UNIV2LPOracle/invalid-oracle-0-price"); require(p1 != 0, "UNIV2LPOracle/invalid-oracle-1-price"); uint256 supply = DSToken(src).totalSupply(); require(preq < 2 ** 128, "UNIV2LPOracle/quote-overflow"); }
4,581,494
[ 1, 4047, 731, 400, 264, 3324, 434, 640, 291, 91, 438, 4501, 372, 24237, 2845, 968, 400, 264, 3324, 434, 640, 291, 91, 438, 4501, 372, 24237, 2845, 4826, 28544, 19827, 854, 6205, 72, 598, 6549, 15105, 5314, 587, 9903, 968, 511, 52, 1147, 14467, 1220, 11096, 1410, 506, 9391, 17, 455, 17175, 5456, 364, 2430, 598, 8572, 3551, 578, 8572, 4587, 19827, 16, 487, 326, 302, 25442, 460, 434, 1517, 20501, 1410, 328, 1385, 316, 279, 284, 1826, 715, 25934, 1048, 15255, 434, 326, 1147, 19827, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6520, 1435, 2713, 1135, 261, 11890, 10392, 3862, 13, 288, 203, 3639, 1351, 291, 91, 438, 58, 22, 4154, 8804, 12, 4816, 2934, 8389, 5621, 203, 203, 3639, 261, 11890, 17666, 436, 20, 16, 2254, 17666, 436, 21, 16, 13, 273, 1351, 291, 91, 438, 58, 22, 4154, 8804, 12, 4816, 2934, 588, 607, 264, 3324, 5621, 203, 3639, 2583, 12, 86, 20, 405, 374, 597, 436, 21, 405, 374, 16, 315, 2124, 8188, 22, 48, 2419, 16873, 19, 5387, 17, 455, 264, 3324, 8863, 203, 203, 3639, 2583, 12, 84, 20, 480, 374, 16, 315, 2124, 8188, 22, 48, 2419, 16873, 19, 5387, 17, 280, 16066, 17, 20, 17, 8694, 8863, 203, 3639, 2583, 12, 84, 21, 480, 374, 16, 315, 2124, 8188, 22, 48, 2419, 16873, 19, 5387, 17, 280, 16066, 17, 21, 17, 8694, 8863, 203, 203, 3639, 2254, 5034, 14467, 273, 463, 882, 969, 12, 4816, 2934, 4963, 3088, 1283, 5621, 203, 203, 3639, 2583, 12, 1484, 85, 411, 576, 2826, 8038, 16, 315, 2124, 8188, 22, 48, 2419, 16873, 19, 6889, 17, 11512, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xae0Ee0A63A2cE6BaeEFFE56e7714FB4EFE48D419/sources/Common.sol
/ NOLINTNEXTLINE: low-level-calls.
function safeTokenContractCall(address tokenAddress, bytes memory callData) internal { require(isContract(tokenAddress), "BAD_TOKEN_ADDRESS"); (bool success, bytes memory returndata) = tokenAddress.call(callData); require(success, string(returndata)); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED"); } } and that its id hash (as infered fromn identify()) matched the expected one.
2,780,727
[ 1, 19, 423, 1741, 3217, 25539, 5997, 30, 4587, 17, 2815, 17, 12550, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 1345, 8924, 1477, 12, 2867, 1147, 1887, 16, 1731, 3778, 745, 751, 13, 2713, 288, 203, 3639, 2583, 12, 291, 8924, 12, 2316, 1887, 3631, 315, 16234, 67, 8412, 67, 15140, 8863, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 1147, 1887, 18, 1991, 12, 1991, 751, 1769, 203, 3639, 2583, 12, 4768, 16, 533, 12, 2463, 892, 10019, 203, 203, 3639, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 2583, 12, 21457, 18, 3922, 12, 2463, 892, 16, 261, 6430, 13, 3631, 315, 8412, 67, 22040, 67, 11965, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 1377, 471, 716, 2097, 612, 1651, 261, 345, 12455, 329, 628, 82, 9786, 10756, 4847, 326, 2665, 1245, 18, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x96891803326B5079Cc96898e61dE5EB7117FB8Be/sources/contracts/Cheezburger.sol
Anti-bot and anti-whale mappings and variables exclude 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 CheezBurgerToken is ERC20Burnable, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public teamWallet; address public operationalWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public blacklistRenounced = false; mapping(address => bool) blacklisted; uint256 public buyTotalFees; uint256 public buyTeamFee; uint256 public buyLiquidityFee; uint256 public buyOperationalFee; uint256 public sellTotalFees; uint256 public sellTeamFee; uint256 public sellLiquidityFee; uint256 public sellOperationalFee; uint256 public tokensForTeam; uint256 public tokensForLiquidity; uint256 public tokensForOperations; 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 teamWalletUpdated( address indexed newWallet, address indexed oldWallet ); event operationalWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); CheezBurgerToken pragma solidity 0.8.20; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/interfaces/IERC20Metadata.sol"; import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IUniswapV2Factory} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import {IUniswapV2Router02} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; constructor(address _teamWallet, address _v2Router) ERC20("CheezBurgerToken", "$CZBR") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( _v2Router ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); buyTeamFee = _buyTeamFee; buyLiquidityFee = _buyLiquidityFee; buyOperationalFee = _buyOperationalFee; buyTotalFees = buyTeamFee + buyLiquidityFee + buyOperationalFee; sellTeamFee = _sellTeamFee; sellLiquidityFee = _sellLiquidityFee; sellOperationalFee = _sellOperationalFee; sellTotalFees = sellTeamFee + sellLiquidityFee + sellOperationalFee; teamWallet = _teamWallet; operationalWallet = 0xAb98C50f3fFC335B755b1C4C8B0FE41317ab2996; 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() external onlyOwner { tradingActive = true; swapEnabled = true; } function disableTrading() external onlyOwner { tradingActive = false; swapEnabled = false; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = 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() * 5) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.5%" ); maxTransactionAmount = newNum * (10 ** 18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 10) / 1000) / 1e18, "Cannot set maxWallet lower than 1.0%" ); maxWallet = newNum * (10 ** 18); } function excludeFromMaxTransaction( address updAds, bool isEx ) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _buyTeamFee, uint256 _buyLiquidityFee, uint256 _buyOperationalFee ) external onlyOwner { buyTeamFee = _buyTeamFee; buyLiquidityFee = _buyLiquidityFee; buyOperationalFee = _buyOperationalFee; buyTotalFees = buyTeamFee + buyLiquidityFee + buyOperationalFee; require(buyTotalFees <= 50, "Buy fees must be <= 5%"); } function updateSellFees( uint256 _sellTeamFee, uint256 _sellLiquidityFee, uint256 _sellOperationalFee ) external onlyOwner { sellTeamFee = _sellTeamFee; sellLiquidityFee = _sellLiquidityFee; sellOperationalFee = _sellOperationalFee; sellTotalFees = sellTeamFee + sellLiquidityFee + sellOperationalFee; require(sellTotalFees <= 100, "Sell fees must be <= 10%"); } 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 updateTeamWallet( address newTeamWallet ) external onlyOwner { emit teamWalletUpdated(newTeamWallet, teamWallet); teamWallet = newTeamWallet; } function updateOperationalWallet(address newWallet) external onlyOwner { emit operationalWalletUpdated(newWallet, operationalWallet); operationalWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function isBlacklisted(address account) public view returns (bool) { return blacklisted[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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"); require(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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"); require(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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"); require(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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(!blacklisted[from], "Sender blacklisted"); require(!blacklisted[to], "Receiver blacklisted"); 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." ); } 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; } 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(1000); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForOperations += (fees * sellOperationalFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(1000); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForOperations += (fees * buyOperationalFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / 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 + tokensForTeam + tokensForOperations; 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 ethForTeam = ethBalance.mul(tokensForTeam).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForLiquidity = ethBalance - ethForTeam - ethForOperations; tokensForLiquidity = 0; tokensForTeam = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(teamWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTeam + tokensForOperations; 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 ethForTeam = ethBalance.mul(tokensForTeam).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForLiquidity = ethBalance - ethForTeam - ethForOperations; tokensForLiquidity = 0; tokensForTeam = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(teamWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTeam + tokensForOperations; 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 ethForTeam = ethBalance.mul(tokensForTeam).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForLiquidity = ethBalance - ethForTeam - ethForOperations; tokensForLiquidity = 0; tokensForTeam = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(teamWallet).call{ value: address(this).balance }(""); } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / (success, ) = address(operationalWallet).call{value: ethForOperations}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTeam + tokensForOperations; 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 ethForTeam = ethBalance.mul(tokensForTeam).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForLiquidity = ethBalance - ethForTeam - ethForOperations; tokensForLiquidity = 0; tokensForTeam = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(teamWallet).call{ value: address(this).balance }(""); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTeam + tokensForOperations; 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 ethForTeam = ethBalance.mul(tokensForTeam).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div( totalTokensToSwap - (tokensForLiquidity / 2) ); uint256 ethForLiquidity = ethBalance - ethForTeam - ethForOperations; tokensForLiquidity = 0; tokensForTeam = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(teamWallet).call{ value: address(this).balance }(""); } function withdrawStuckCheezBurger() external onlyOwner { uint256 balance = IERC20(address(this)).balanceOf(address(this)); IERC20(address(this)).transfer(msg.sender, balance); payable(msg.sender).transfer(address(this).balance); } function withdrawStuckToken( address _token, address _to ) external onlyOwner { require(_token != address(0), "_token address cannot be 0"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); IERC20(_token).transfer(_to, _contractBalance); } function withdrawStuckEth(address toAddr) external onlyOwner { require(success); } (bool success, ) = toAddr.call{value: address(this).balance}(""); function renounceBlacklist() public onlyOwner { blacklistRenounced = true; } function blacklist(address _addr) public onlyOwner { require(!blacklistRenounced, "Team has revoked blacklist rights"); require( _addr != address(uniswapV2Pair) && _addr != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "Cannot blacklist token's v2 router or v2 pool." ); blacklisted[_addr] = true; } function blacklistLiquidityPool(address lpAddress) public onlyOwner { require(!blacklistRenounced, "Team has revoked blacklist rights"); require( lpAddress != address(uniswapV2Pair) && lpAddress != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "Cannot blacklist token's v2 router or v2 pool." ); blacklisted[lpAddress] = true; } function unblacklist(address _addr) public onlyOwner { blacklisted[_addr] = false; } }
9,742,463
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4433, 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, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 22682, 6664, 38, 295, 693, 1345, 353, 4232, 39, 3462, 38, 321, 429, 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, 5927, 16936, 31, 203, 565, 1758, 1071, 1674, 287, 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, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 203, 565, 1426, 1071, 11709, 16290, 27373, 273, 629, 31, 203, 377, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 25350, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 8689, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 2988, 287, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 8689, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 2 ]
./full_match/97/0xA3A65C238C8c8d436Bf92e0718f12bc4050f23D7/sources/project_/contracts/VOWLaunchpad.sol
* @notice This method is used to set commission percentage for the launchpad @param _feePercentage Percentage from raised funds to be set as fee/
function setFee(uint256 _feePercentage) external onlyOwner { require( _feePercentage <= 10000, "VOWLaunchpad: fee Percentage should be less than 10000" ); feePercentage = _feePercentage; emit SetFeePercentage(_feePercentage); }
5,021,213
[ 1, 2503, 707, 353, 1399, 358, 444, 1543, 19710, 11622, 364, 326, 8037, 6982, 225, 389, 21386, 16397, 21198, 410, 628, 11531, 284, 19156, 358, 506, 444, 487, 14036, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 14667, 12, 11890, 5034, 389, 21386, 16397, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 389, 21386, 16397, 1648, 12619, 16, 203, 5411, 315, 58, 7306, 9569, 6982, 30, 14036, 21198, 410, 1410, 506, 5242, 2353, 12619, 6, 203, 3639, 11272, 203, 3639, 14036, 16397, 273, 389, 21386, 16397, 31, 203, 3639, 3626, 1000, 14667, 16397, 24899, 21386, 16397, 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 ]
pragma solidity ^0.4.22; //TODO : Store Games in a Map instead of array. See if that has any advantages. contract owned { address owner; modifier onlyOwner() { require(msg.sender == owner); _; } } contract priced { modifier costs(uint256 price) { require(msg.value >= price); _; } } contract SplitStealContract is owned, priced { //Global Variables uint constant STEAL = 0; uint constant SPLIT = 1; mapping(address=>bool) suspended; mapping(address=>uint) totalGamesStarted; mapping(address=>uint) totalGamesParticipated; uint256 contractEarnings = 0; //Game Rules uint256 REGISTRATION_COST = 10**14;// 0.0001 Ether //Editable by Owner uint256 MINIMUM_COST_OF_BET = 10**17;// 0.1 Ether //Editable by Owner uint256 MAXIMUM_COST_OF_BET = 5 * 10**18;//5 Ether //Editable by Owner uint256 STAGE_TIMEOUT = 60*60*24*7;//1 Week //Reward Matrix Parameters uint256 K = 25; //Editable by Owner //Events event RegisterationOpened(uint indexed _gameNumber); event RegisterationClosed(uint indexed _gameNumber); event RevealStart(uint indexed _gameNumber); event RevealStop(uint indexed _gameNumber); event Transferred(uint indexed _gameNumber,address _to, uint256 _amount); event ContractEarnings(uint indexed _gameNumber, uint256 _amount, string _reason); event Disqualified(uint indexed _gameNumber, address indexed _player, bytes32 _encryptedChoice, uint _actualChoice, bytes32 _encryptedActualChoice); event NewGameRules(uint _oldFees, uint _newFees, uint _oldMinBet, uint _newMinBet, uint _oldMaxBet, uint _newMaxBet, uint _oldStageTimeout, uint _newStageTimeout); event NewRewardMatrix(uint _n1, uint _n2, uint _n3, uint _d); event NewRewardPercentage(uint256 _oldK, uint256 _k); event Suspended(address indexed _player); event UnSuspended(address indexed _player); //BET Struct struct Bet { bytes32 encryptedChoice; uint256 betAmount; uint actualChoice; } //GAME Struct struct Game { uint startTime; uint revealTime; uint finishTime; address player1; address player2; uint256 registrationCost; uint256 k; uint stageTimeout; bool registerationOpen; bool revealing; bool lastGameFinished; mapping(address=>address) opponent; mapping(address=>bool) registered; mapping(address=>Bet) bets; mapping(address=>bool) revealed; mapping(address=>bool) disqualified; mapping(address=>bool) claimedReward; mapping(address=>uint256) reward; } Game[] games; constructor() public { owner = msg.sender; } function fund() payable external { contractEarnings = contractEarnings + msg.value; } // UTILITY METHODS STARTS function isEven(uint num) private pure returns(bool _isEven) { uint halfNum = num / 2; return (halfNum * 2) == num; } // UTILITY METHODS END // ADMIN METHODS START function changeOwner(address _to) public onlyOwner { require(_to != address(0)); owner = _to; } /** @dev So Owner can't take away player's money in the middle of the game. Owner can only withdraw earnings of the game contract and not the entire balance. Earnings are calculated after every game is finished, i.e.; when both players have cliamed reward. If a player doens't claim reward for a game, those ether can not be reclaimed until 1 week. After 1 week Owner of contract has power of disqualifying Players who did not finihs the game. FAIR ENOUGH ? */ function transferEarningsToOwner() public onlyOwner { require(address(this).balance >= contractEarnings); uint256 _contractEarnings = contractEarnings; contractEarnings = 0; // VERY IMPORTANT // PREVENTS REENTRANCY ATTACK BY CONTRACT OWNER // contract Earnings need to be set to 0 first, // and then transferred to owner owner.transfer(_contractEarnings); } function suspend(address _player) public onlyOwner returns(bool _suspended){ require(!suspended[_player]); require(_player != owner); suspended[_player] = true; emit Suspended(_player); return true; } function unSuspend(address _player) public onlyOwner returns(bool _unSuspended){ require(suspended[_player]); suspended[_player] = false; emit UnSuspended(_player); return true; } function setRewardPercentageK(uint256 _k) public onlyOwner { //Max earnings is double. require(_k <= 100); emit NewRewardPercentage(K, _k); K = _k; } function setGameRules(uint256 _fees, uint256 _minBet, uint256 _maxBet, uint256 _stageTimeout) public onlyOwner { require(_stageTimeout >= 60*60*24*7);//Owner can't set it to below 1 week require((_fees * 100 ) < _minBet);//Fees will always be less that 1 % of bet require(_minBet < _maxBet); emit NewGameRules(REGISTRATION_COST, _fees, MINIMUM_COST_OF_BET, _minBet, MAXIMUM_COST_OF_BET, _maxBet, STAGE_TIMEOUT, _stageTimeout); REGISTRATION_COST = _fees; MINIMUM_COST_OF_BET = _minBet; MAXIMUM_COST_OF_BET = _maxBet; STAGE_TIMEOUT = _stageTimeout; } //ADMIN METHODS ENDS //VIEW APIs STARTS function getOwner() public view returns(address _owner) { return owner; } function getContractBalance() public view returns(uint256 _balance) { return address(this).balance; } function getContractEarnings() public view returns(uint _earnings) { return contractEarnings; } function getRewardMatrix() public view returns(uint _k) { return (K); } function getGameRules() public view returns(uint256 _fees, uint256 _minBet, uint256 _maxBet, uint256 _stageTimeout) { return (REGISTRATION_COST, MINIMUM_COST_OF_BET, MAXIMUM_COST_OF_BET, STAGE_TIMEOUT); } function getGameState(uint gameNumber) public view returns(bool _registerationOpen, bool _revealing, bool _lastGameFinished, uint _startTime, uint _revealTime, uint _finishTime, uint _stageTimeout) { require(games.length >= gameNumber); Game storage game = games[gameNumber - 1]; return (game.registerationOpen, game.revealing, game.lastGameFinished, game.startTime, game.revealTime, game.finishTime, game.stageTimeout); } function getPlayerState(uint gameNumber) public view returns(bool _suspended, bool _registered, bool _revealed, bool _disqualified, bool _claimedReward, uint256 _betAmount, uint256 _reward) { require(games.length >= gameNumber); uint index = gameNumber - 1; address player = msg.sender; uint256 betAmount = games[index].bets[player].betAmount; return (suspended[player], games[index].registered[player], games[index].revealed[player], games[index].disqualified[player], games[index].claimedReward[player], betAmount, games[index].reward[player] ); } function getTotalGamesStarted() public view returns(uint _totalGames) { return totalGamesStarted[msg.sender]; } function getTotalGamesParticipated() public view returns(uint _totalGames) { return totalGamesParticipated[msg.sender]; } function getTotalGames() public view returns(uint _totalGames) { return games.length; } //VIEW APIs ENDS //GAME PLAY STARTS function startGame(uint256 _betAmount, bytes32 _encryptedChoice) public payable costs(_betAmount) returns(uint _gameNumber) { address player = msg.sender; require(!suspended[player]); require(_betAmount >= MINIMUM_COST_OF_BET); require(_betAmount <= MAXIMUM_COST_OF_BET); Game memory _game = Game(now, now, now, player, address(0), REGISTRATION_COST, K, STAGE_TIMEOUT, true, false, false); games.push(_game); Game storage game = games[games.length-1]; game.registered[player] = true; game.bets[player] = Bet(_encryptedChoice, _betAmount, 0); totalGamesStarted[player] = totalGamesStarted[player] + 1; emit RegisterationOpened(games.length); return games.length; } function joinGame(uint _gameNumber, uint256 _betAmount, bytes32 _encryptedChoice) public payable costs(_betAmount) { require(games.length >= _gameNumber); Game storage game = games[_gameNumber-1]; address player = msg.sender; require(game.registerationOpen); require(game.player1 != player); // Can also put ```require(game.registered[player]);``` meaning, Same player cannot join the game. require(!suspended[player]); require(_betAmount >= MINIMUM_COST_OF_BET); require(_betAmount <= MAXIMUM_COST_OF_BET); require(game.player2 == address(0)); game.player2 = player; game.registered[player] = true; game.bets[player] = Bet(_encryptedChoice, _betAmount, 0); game.registerationOpen = false; game.revealing = true; game.revealTime = now; // Set Game Reveal time in order to resolve dead lock if no one claims reward. game.finishTime = now; // If both do not reveal for one week, Admin can immidiately finish game. game.opponent[game.player1] = game.player2; game.opponent[game.player2] = game.player1; totalGamesParticipated[player] = totalGamesParticipated[player] + 1; emit RegisterationClosed(_gameNumber); emit RevealStart(_gameNumber); } function reveal(uint _gameNumber, uint256 _choice) public { require(games.length >= _gameNumber); Game storage game = games[_gameNumber-1]; require(game.revealing); address player = msg.sender; require(!suspended[player]); require(game.registered[player]); require(!game.revealed[player]); game.revealed[player] = true; game.bets[player].actualChoice = _choice; bytes32 encryptedChoice = game.bets[player].encryptedChoice; bytes32 encryptedActualChoice = keccak256(_choice); if( encryptedActualChoice != encryptedChoice) { game.disqualified[player] = true; //Mark them as Claimed Reward so that //contract earnings can be accounted for game.claimedReward[player] = true; game.reward[player] = 0; if (game.disqualified[game.opponent[player]]) { uint256 gameEarnings = game.bets[player].betAmount + game.bets[game.opponent[player]].betAmount; contractEarnings = contractEarnings + gameEarnings; emit ContractEarnings(_gameNumber, gameEarnings, "BOTH_DISQUALIFIED"); } emit Disqualified(_gameNumber, player, encryptedChoice, _choice, encryptedActualChoice); } if(game.revealed[game.player1] && game.revealed[game.player2]) { game.revealing = false; game.lastGameFinished = true; game.finishTime = now; //Set Game finish time in order to resolve dead lock if no one claims reward. emit RevealStop(_gameNumber); } } //GAME PLAY ENDS //REWARD WITHDRAW STARTS function ethTransfer(uint gameNumber, address _to, uint256 _amount) private { require(!suspended[_to]); require(_to != address(0)); if ( _amount > games[gameNumber-1].registrationCost) { //Take game Commission uint256 amount = _amount - games[gameNumber-1].registrationCost; require(address(this).balance >= amount); _to.transfer(amount); emit Transferred(gameNumber, _to, amount); } } function claimRewardK(uint gameNumber) public returns(bool _claimedReward) { require(games.length >= gameNumber); Game storage game = games[gameNumber-1]; address player = msg.sender; require(!suspended[player]); require(!game.claimedReward[player]); uint commission = games[gameNumber-1].registrationCost; if (game.registerationOpen) { game.claimedReward[player] = true; game.registerationOpen = false; game.lastGameFinished = true; if ( now > (game.startTime + game.stageTimeout)) { //No commision if game was open till stage timeout. commission = 0; } game.reward[player] = game.bets[player].betAmount - commission; if (commission > 0) { contractEarnings = contractEarnings + commission; emit ContractEarnings(gameNumber, commission, "GAME_ABANDONED"); } //Bet amount can't be less than commission. //Hence no -ve check is required ethTransfer(gameNumber, player, game.bets[player].betAmount); return true; } require(game.lastGameFinished); require(!game.disqualified[player]); require(game.registered[player]); require(game.revealed[player]); require(!game.claimedReward[player]); game.claimedReward[player] = true; address opponent = game.opponent[player]; uint256 reward = 0; uint256 gameReward = 0; uint256 totalBet = (game.bets[player].betAmount + game.bets[opponent].betAmount); if ( game.disqualified[opponent]) { gameReward = ((100 + game.k) * game.bets[player].betAmount) / 100; reward = gameReward < totalBet ? gameReward : totalBet; //Min (X+Y, (100+K)*X/100) game.reward[player] = reward - commission; //Min (X+Y, (100+K)*X/100) can't be less than commision. //Hence no -ve check is required contractEarnings = contractEarnings + (totalBet - game.reward[player]); emit ContractEarnings(gameNumber, (totalBet - game.reward[player]), "OPPONENT_DISQUALIFIED"); ethTransfer(gameNumber, player, reward); return true; } if ( !isEven(game.bets[player].actualChoice) && !isEven(game.bets[opponent].actualChoice) ) { // Split Split reward = (game.bets[player].betAmount + game.bets[opponent].betAmount) / 2; game.reward[player] = reward - commission; //(X+Y)/2 can't be less than commision. //Hence no -ve check is required if ( game.claimedReward[opponent] ) { uint256 gameEarnings = (totalBet - game.reward[player] - game.reward[opponent]); contractEarnings = contractEarnings + gameEarnings; emit ContractEarnings(gameNumber, gameEarnings, "SPLIT_SPLIT"); } ethTransfer(gameNumber, player, reward); return true; } if ( !isEven(game.bets[player].actualChoice) && isEven(game.bets[opponent].actualChoice) ) { // Split Steal game.reward[player] = 0; if ( game.claimedReward[opponent] ) { gameEarnings = (totalBet - game.reward[player] - game.reward[opponent]); contractEarnings = contractEarnings + gameEarnings; emit ContractEarnings(gameNumber, gameEarnings, "SPLIT_STEAL"); } return true; } if ( isEven(game.bets[player].actualChoice) && !isEven(game.bets[opponent].actualChoice) ) { // Steal Split gameReward = (((100 + game.k) * game.bets[player].betAmount)/100); reward = gameReward < totalBet ? gameReward : totalBet; game.reward[player] = reward - commission; //Min (X+Y, (100+K)*X/100) can't be less than commision. //Hence no -ve check is required if ( game.claimedReward[opponent] ) { gameEarnings = (totalBet - game.reward[player] - game.reward[opponent]); contractEarnings = contractEarnings + gameEarnings; emit ContractEarnings(gameNumber, gameEarnings, "STEAL_SPLIT"); } ethTransfer(gameNumber, player, reward); return true; } if ( isEven(game.bets[player].actualChoice) && isEven(game.bets[opponent].actualChoice) ) { // Steal Steal reward = 0; if( game.bets[player].betAmount > game.bets[opponent].betAmount) { //((100-K)*(X-Y)/2)/100 will always be less than X+Y so no need for min check on X+Y and reward reward = ((100 - game.k) * (game.bets[player].betAmount - game.bets[opponent].betAmount) / 2) / 100; } if(reward > 0) { //((100-K)*(X-Y)/2)/100 CAN BE LESS THAN COMMISSION. game.reward[player] = reward > commission ? reward - commission : 0; } if ( game.claimedReward[opponent] ) { gameEarnings = (totalBet - game.reward[player] - game.reward[opponent]); contractEarnings = contractEarnings + gameEarnings; emit ContractEarnings(gameNumber, gameEarnings, "STEAL_STEAL"); } ethTransfer(gameNumber, player, reward); return true; } } //REWARD WITHDRAW ENDS //OWNER OVERRIDE SECTION STARTS /** * Give back to game creator instead of consuming to contract. * So in case Game owner has PTSD and wants al game finished, * Game owner will call this on game which is in registeration open * state since past stage timeout. * Do some good :) * ALTHOUGH if game creator wants to abandon after stage timeout * No fees is charged. See claimReward Method for that. */ function ownerAbandonOverride(uint _gameNumber) private returns(bool _overriden) { Game storage game = games[_gameNumber-1]; if (game.registerationOpen) { if (now > (game.startTime + game.stageTimeout)) { game.claimedReward[game.player1] = true; game.registerationOpen = false; game.lastGameFinished = true; game.reward[game.player1] = game.bets[game.player1].betAmount; //Do not cut commision as no one came to play. //This also incentivisies users to keep the game open for long time. ethTransfer(_gameNumber, game.player1, game.bets[game.player1].betAmount); return true; } } return false; } /** * If both palayer(s) does(-es) not reveal choice in time they get disqualified. * If both players do not reveal choice in time, Game's earnings are updated. * If one of the player does not reveal choice, then game's earnings are not updated. * Player who has revealed is given chance to claim reward. */ function ownerRevealOverride(uint _gameNumber) private returns(bool _overriden) { Game storage game = games[_gameNumber-1]; if ( game.revealing) { if (now > (game.revealTime + game.stageTimeout)) { if(!game.revealed[game.player1] && !game.revealed[game.player1]) { //Mark Player as following, // 1.)Revealed (To maintain sane state of game) // 2.)Disqualified (Since player did not finish the game in time) // 3.)Claimed Reward ( So that contract earnings can be accounted for) // Also set reward amount as 0 game.revealed[game.player1] = true; game.disqualified[game.player1] = true; game.claimedReward[game.player1] = true; game.reward[game.player1] = 0; emit Disqualified(_gameNumber, game.player1, "", 0, ""); game.revealed[game.player2] = true; game.disqualified[game.player2] = true; game.claimedReward[game.player2] = true; game.reward[game.player2] = 0; emit Disqualified(_gameNumber, game.player2, "", 0, ""); game.finishTime = now; uint256 gameEarnings = game.bets[game.player1].betAmount + game.bets[game.player2].betAmount; contractEarnings = contractEarnings + gameEarnings; emit ContractEarnings(_gameNumber, gameEarnings, "BOTH_NO_REVEAL"); } else if (game.revealed[game.player1] && !game.revealed[game.player2]) { game.revealed[game.player2] = true; game.disqualified[game.player2] = true; game.claimedReward[game.player2] = true; game.reward[game.player2] = 0; emit Disqualified(_gameNumber, game.player2, "", 0, ""); game.finishTime = now; } else if (!game.revealed[game.player1] && game.revealed[game.player2]) { game.revealed[game.player1] = true; game.disqualified[game.player1] = true; game.claimedReward[game.player1] = true; game.reward[game.player1] = 0; emit Disqualified(_gameNumber, game.player1, "", 0, ""); game.finishTime = now; } game.revealing = false; game.lastGameFinished = true; emit RevealStop(_gameNumber); return true; } } return false; } /** * If both palayer(s) does(-es) not claim reward in time * they loose their chance to claim reward. * Game earnings are calculated as if this gets executed successully, * both players have claimed rewards eseentialy. */ function ownerClaimOverride(uint _gameNumber) private returns(bool _overriden) { Game storage game = games[_gameNumber-1]; if ( game.lastGameFinished) { if (now > (game.finishTime + game.stageTimeout)) { if(!game.claimedReward[game.player1] && !game.claimedReward[game.player1]) { game.claimedReward[game.player1] = true; game.reward[game.player1] = 0; game.claimedReward[game.player2] = true; game.reward[game.player2] = 0; } else if (game.claimedReward[game.player1] && !game.claimedReward[game.player2]) { game.claimedReward[game.player2] = true; game.reward[game.player2] = 0; } else if (!game.claimedReward[game.player1] && game.claimedReward[game.player2]) { game.claimedReward[game.player1] = true; game.reward[game.player1] = 0; } else { //Both players have alreay claimed reward. return false; } uint256 totalBet = (game.bets[game.player1].betAmount + game.bets[game.player2].betAmount); uint gameEarnings = totalBet - game.reward[game.player1] - game.reward[game.player2]; contractEarnings = contractEarnings + gameEarnings; emit ContractEarnings(_gameNumber, gameEarnings, "OWNER_CLAIM_OVERRIDE"); } } } function ownerOverride(uint _gameNumber) public onlyOwner returns(bool _overriden){ if (msg.sender == owner) { if( ownerAbandonOverride(_gameNumber) || ownerRevealOverride(_gameNumber) || ownerClaimOverride(_gameNumber) ) { return true; } } return false; } //OWNER OVERRIDE SECTION ENDS }
ADMIN METHODS START
function changeOwner(address _to) public onlyOwner { require(_to != address(0)); owner = _to; } Earnings are calculated after every game is finished, i.e.; when both players have cliamed reward. If a player doens't claim reward for a game, those ether can not be reclaimed until 1 week. After 1 week Owner of contract has power of disqualifying Players who did not finihs the game. FAIR ENOUGH ?
12,181,111
[ 1, 15468, 10152, 55, 10485, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 5541, 12, 2867, 389, 869, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 3639, 3410, 273, 389, 869, 31, 203, 565, 289, 203, 565, 512, 1303, 899, 854, 8894, 1839, 3614, 7920, 353, 6708, 16, 277, 18, 73, 18, 31, 1347, 3937, 18115, 203, 565, 1240, 4942, 2808, 19890, 18, 971, 279, 7291, 741, 773, 1404, 7516, 19890, 364, 279, 7920, 16, 5348, 225, 2437, 7010, 565, 848, 486, 506, 283, 14784, 329, 3180, 404, 4860, 18, 7360, 404, 4860, 16837, 434, 6835, 711, 7212, 434, 1015, 3369, 1164, 310, 7010, 565, 3008, 3907, 10354, 5061, 486, 574, 77, 4487, 326, 7920, 18, 15064, 7937, 25033, 57, 16715, 692, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // import "hardhat/console.sol"; import {IERC20} from "./interfaces/IERC20.sol"; import {LibERC20} from "./libraries/LibERC20.sol"; import "./libraries/LibMath.sol"; import {RLPReader} from "./libraries/RLPReader.sol"; import {ITokenPredicate} from "./interfaces/ITokenPredicate.sol"; interface ILendingPool { function getReserveNormalizedIncome(address _asset) external view returns (uint256); } interface IAToken { function POOL() external returns(ILendingPool); function UNDERLYING_ASSET_ADDRESS() external returns(address); } struct AppStorage { address manager; bool init; } contract ERC20Predicate is ITokenPredicate { AppStorage s; using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; modifier onlyManager() { require(s.manager == msg.sender, "Caller is not manager"); _; } bytes32 public constant TRANSFER_EVENT_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; event LockedERC20( address indexed depositor, address indexed depositReceiver, address indexed rootToken, uint256 amount ); function initialize(address _manager) external { require(!s.init, "Already initialized"); s.init = true; s.manager = _manager; } function getMATokenValue(address _aTokenAddress, uint256 _aTokenValue) external returns (uint256 maTokenValue_) { ILendingPool pool = IAToken(_aTokenAddress).POOL(); uint256 liquidityIndex = pool.getReserveNormalizedIncome(IAToken(_aTokenAddress).UNDERLYING_ASSET_ADDRESS()); maTokenValue_ = LibMath.p27Div(_aTokenValue, liquidityIndex); } /** * @notice Lock ERC20 tokens for deposit, callable only by manager * @param depositor Address who wants to deposit tokens * @param depositReceiver Address (address) who wants to receive tokens on child chain * @param rootToken Token which gets deposited * @param depositData ABI encoded amount */ function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external override onlyManager() { (uint256 maTokenValue, uint256 maxATokenValue) = abi.decode(depositData, (uint256, uint256)); ILendingPool pool = IAToken(rootToken).POOL(); uint256 liquidityIndex = pool.getReserveNormalizedIncome(IAToken(rootToken).UNDERLYING_ASSET_ADDRESS()); uint256 aTokenValue = LibMath.p27Mul(maTokenValue, liquidityIndex); require(aTokenValue <= maxATokenValue, "Too much aToken slippage occurred on transfer to matic"); emit LockedERC20(depositor, depositReceiver, rootToken, aTokenValue); LibERC20.transferFrom(rootToken, depositor, address(this), aTokenValue); } /** * @notice Validates log signature, from and to address * then sends the correct amount to withdrawer * callable only by manager * @param rootToken Token which gets withdrawn * @param log Valid ERC20 burn log from child chain */ function exitTokens( address, address rootToken, bytes memory log ) public override onlyManager() { RLPReader.RLPItem[] memory logRLPList = log.toRlpItem().toList(); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics require( bytes32(logTopicRLPList[0].toUint()) == TRANSFER_EVENT_SIG, // topic0 is event sig "ERC20Predicate: INVALID_SIGNATURE" ); address withdrawer = address(logTopicRLPList[1].toUint()); // topic1 is from address require( address(logTopicRLPList[2].toUint()) == address(0), // topic2 is to address "ERC20Predicate: INVALID_RECEIVER" ); uint256 maTokenAmount = logRLPList[2].toUint(); ILendingPool pool = IAToken(rootToken).POOL(); uint256 liquidityIndex = pool.getReserveNormalizedIncome(IAToken(rootToken).UNDERLYING_ASSET_ADDRESS()); uint256 aTokenAmount = LibMath.p27Mul(maTokenAmount, liquidityIndex); LibERC20.transfer( rootToken, withdrawer, aTokenAmount ); } }
* @notice Validates log signature, from and to address then sends the correct amount to withdrawer callable only by manager @param rootToken Token which gets withdrawn @param log Valid ERC20 burn log from child chain/
function exitTokens( address, address rootToken, bytes memory log ) public override onlyManager() { RLPReader.RLPItem[] memory logRLPList = log.toRlpItem().toList(); require( "ERC20Predicate: INVALID_SIGNATURE" ); require( "ERC20Predicate: INVALID_RECEIVER" ); uint256 maTokenAmount = logRLPList[2].toUint(); ILendingPool pool = IAToken(rootToken).POOL(); uint256 liquidityIndex = pool.getReserveNormalizedIncome(IAToken(rootToken).UNDERLYING_ASSET_ADDRESS()); uint256 aTokenAmount = LibMath.p27Mul(maTokenAmount, liquidityIndex); LibERC20.transfer( rootToken, withdrawer, aTokenAmount ); }
1,797,620
[ 1, 9594, 613, 3372, 16, 628, 471, 358, 1758, 1508, 9573, 326, 3434, 3844, 358, 598, 9446, 264, 4140, 1338, 635, 3301, 225, 1365, 1345, 3155, 1492, 5571, 598, 9446, 82, 225, 613, 2364, 4232, 39, 3462, 18305, 613, 628, 1151, 2687, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2427, 5157, 12, 203, 3639, 1758, 16, 203, 3639, 1758, 1365, 1345, 16, 203, 3639, 1731, 3778, 613, 203, 565, 262, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 1338, 1318, 1435, 203, 565, 288, 203, 3639, 534, 14461, 2514, 18, 54, 48, 1102, 874, 8526, 3778, 613, 54, 14461, 682, 273, 613, 18, 869, 54, 9953, 1180, 7675, 869, 682, 5621, 203, 203, 3639, 2583, 12, 203, 5411, 315, 654, 39, 3462, 8634, 30, 10071, 67, 26587, 6, 203, 3639, 11272, 203, 203, 203, 3639, 2583, 12, 203, 5411, 315, 654, 39, 3462, 8634, 30, 10071, 67, 27086, 45, 2204, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 10843, 1345, 6275, 273, 613, 54, 14461, 682, 63, 22, 8009, 869, 5487, 5621, 203, 3639, 467, 48, 2846, 2864, 2845, 273, 467, 789, 969, 12, 3085, 1345, 2934, 20339, 5621, 203, 3639, 2254, 5034, 4501, 372, 24237, 1016, 273, 2845, 18, 588, 607, 6527, 15577, 382, 5624, 12, 45, 789, 969, 12, 3085, 1345, 2934, 31625, 7076, 1360, 67, 3033, 4043, 67, 15140, 10663, 203, 3639, 2254, 5034, 279, 1345, 6275, 273, 10560, 10477, 18, 84, 5324, 27860, 12, 2540, 1345, 6275, 16, 4501, 372, 24237, 1016, 1769, 203, 3639, 10560, 654, 39, 3462, 18, 13866, 12, 203, 5411, 1365, 1345, 16, 7010, 5411, 598, 9446, 264, 16, 203, 5411, 279, 1345, 6275, 203, 3639, 11272, 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 ]
pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IYFIArbableERC20 is IERC20 { function arbCall(address account, uint amount) external; } contract YFVIIFarm is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accTokensPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accTokensPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Tokens to distribute per block. uint256 lastRewardBlock; // Last block number that Tokens distribution occurs. uint256 accTokensPerShare; // Accumulated Tokens per share, times 1e12. See below. } // Token IYFIArbableERC20 public token; // Dev address. address public devaddr; // Block number when staking period ends. uint256 public stakingEndBlock; // Tokens created per block. uint256 public tokensPerBlock; // How long before tokens become available after minting uint256 public maturationPeriod; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; // Block number that a wallet last deposited LP tokens mapping (address => uint256) public latestDepositBlockNumberForWallet; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IYFIArbableERC20 _token, uint256 _tokensPerBlock, uint256 _startBlock, uint256 _stakingEndBlock, uint256 _maturationPeriod ) public { token = _token; devaddr = msg.sender; tokensPerBlock = _tokensPerBlock; stakingEndBlock = _stakingEndBlock; startBlock = _startBlock; maturationPeriod = _maturationPeriod; } function poolLength() external view returns (uint256) { return poolInfo.length; } function setMaturationPeriod(uint256 _maturationPeriod) public onlyOwner { maturationPeriod = _maturationPeriod; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTokensPerShare: 0 })); } // Update the given pool's token allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending tokens on frontend. function pendingTokens(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTokensPerShare = pool.accTokensPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 tokenReward = tokensPerBlock.mul(pool.allocPoint).div(totalAllocPoint); accTokensPerShare = accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTokensPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock || block.number >= stakingEndBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 tokenReward = tokensPerBlock.mul(pool.allocPoint).div(totalAllocPoint); token.arbCall(devaddr, tokenReward.div(10)); token.arbCall(address(this), tokenReward); pool.accTokensPerShare = pool.accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to contract for token allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); latestDepositBlockNumberForWallet[msg.sender] = block.number; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from contract. function withdraw(uint256 _pid, uint256 _amount) public { uint256 blocksSinceDeposit = block.number - latestDepositBlockNumberForWallet[msg.sender]; if(blocksSinceDeposit < maturationPeriod) { revert(); } PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe token transfer function, just in case a rounding error causes pool to not have enough tokens. function safeTokenTransfer(address _to, uint256 _amount) internal { uint256 tokenBalance = token.balanceOf(address(this)); if (_amount > tokenBalance) { token.transfer(_to, tokenBalance); } else { token.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Withdraw LP tokens from contract.
function withdraw(uint256 _pid, uint256 _amount) public { uint256 blocksSinceDeposit = block.number - latestDepositBlockNumberForWallet[msg.sender]; if(blocksSinceDeposit < maturationPeriod) { revert(); } PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
14,547,418
[ 1, 1190, 9446, 511, 52, 2430, 628, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2254, 5034, 4398, 9673, 758, 1724, 273, 1203, 18, 2696, 300, 4891, 758, 1724, 1768, 1854, 1290, 16936, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 12, 7996, 9673, 758, 1724, 411, 4834, 872, 5027, 13, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 5157, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 3639, 4183, 1345, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 5157, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xe7f1754eC01d51c5eB236b28F67255ea87C2543f/sources/StakingContract.sol
Amount of tokens staked by the staker Staked token idsStakedToken[] stakedTokens; Last time of the rewards were calculated for this user Calculated, but unclaimed rewards for the User. The rewards are calculated each time the user writes to the Smart Contract
struct TokenStaker{ uint256 amountStaked; uint256 timeOfLastUpdate; uint256 unclaimedRewards; bool hasStaked; } mapping(address => TokenStaker) public tokenStakers; address[] public stakers;
782,609
[ 1, 6275, 434, 2430, 384, 9477, 635, 326, 384, 6388, 934, 9477, 1147, 3258, 510, 9477, 1345, 8526, 384, 9477, 5157, 31, 6825, 813, 434, 326, 283, 6397, 4591, 8894, 364, 333, 729, 15994, 690, 16, 1496, 6301, 80, 4581, 329, 283, 6397, 364, 326, 2177, 18, 1021, 283, 6397, 854, 8894, 1517, 813, 326, 729, 7262, 358, 326, 19656, 13456, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 3155, 510, 6388, 95, 203, 3639, 2254, 5034, 3844, 510, 9477, 31, 203, 203, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 203, 3639, 2254, 5034, 6301, 80, 4581, 329, 17631, 14727, 31, 203, 203, 3639, 1426, 711, 510, 9477, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 12, 2867, 516, 3155, 510, 6388, 13, 1071, 1147, 510, 581, 414, 31, 203, 203, 203, 565, 1758, 8526, 1071, 384, 581, 414, 31, 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 ]
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract usingEthereumV2Erc20Consts { uint constant TOKEN_DECIMALS = 18; uint8 constant TOKEN_DECIMALS_UINT8 = 18; uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; uint constant TEAM_TOKENS = 0 * TOKEN_DECIMAL_MULTIPLIER; uint constant BOUNTY_TOKENS = 0 * TOKEN_DECIMAL_MULTIPLIER; uint constant PREICO_TOKENS = 0 * TOKEN_DECIMAL_MULTIPLIER; uint constant MINIMAL_PURCHASE = 0.00001 ether; address constant TEAM_ADDRESS = 0x78cd8f794686ee8f6644447e961ef52776edf0cb; address constant BOUNTY_ADDRESS = 0xff823588500d3ecd7777a1cfa198958df4deea11; address constant PREICO_ADDRESS = 0xff823588500d3ecd7777a1cfa198958df4deea11; address constant COLD_WALLET = 0x439415b03708bde585856b46666f34b65af6a5c3; string constant TOKEN_NAME = "Ethereum V2 Erc20"; bytes32 constant TOKEN_SYMBOL = "ETH20"; } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { 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 > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract EthereumV2Erc20 is usingEthereumV2Erc20Consts, MintableToken, BurnableToken { /** * @dev Pause token transfer. After successfully finished crowdsale it becomes true. */ bool public paused = false; /** * @dev Accounts who can transfer token even if paused. Works only during crowdsale. */ mapping(address => bool) excluded; function name() constant public returns (string _name) { return TOKEN_NAME; } function symbol() constant public returns (bytes32 _symbol) { return TOKEN_SYMBOL; } function decimals() constant public returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function crowdsaleFinished() onlyOwner { paused = false; finishMinting(); } function addExcluded(address _toExclude) onlyOwner { excluded[_toExclude] = true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(!paused || excluded[_from]); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) returns (bool) { require(!paused || excluded[msg.sender]); return super.transfer(_to, _value); } /** * @dev Burn tokens from the specified address. * @param _from address The address which you want to burn tokens from. * @param _value uint The amount of tokens to be burned. */ function burnFrom(address _from, uint256 _value) returns (bool) { require(_value > 0); var allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); totalSupply = totalSupply.sub(_value); allowed[_from][msg.sender] = allowance.sub(_value); Burn(_from, _value); return true; } } contract EthereumV2Erc20RateProviderI { /** * @dev Calculate actual rate using the specified parameters. * @param buyer Investor (buyer) address. * @param totalSold Amount of sold tokens. * @param amountWei Amount of wei to purchase. * @return ETH to Token rate. */ function getRate(address buyer, uint totalSold, uint amountWei) public constant returns (uint); /** * @dev rate scale (or divider), to support not integer rates. * @return Rate divider. */ function getRateScale() public constant returns (uint); /** * @return Absolute base rate. */ function getBaseRate() public constant returns (uint); } contract EthereumV2Erc20RateProvider is usingEthereumV2Erc20Consts, EthereumV2Erc20RateProviderI, Ownable { // rate calculate accuracy uint constant RATE_SCALE = 1; // Start time: Human time (GMT): Sunday, May 5, 2019 5:05:05 PM // End time: Human time (GMT): Saturday, May 5, 2029 5:05:05 PM // Guaranteed by 100% ETH. // Contract to buy 100% token to burn off. // Service fee 2%. 98% of the funds were bought back by all contracts and then burned. uint constant STEP_9 = 50000 * TOKEN_DECIMAL_MULTIPLIER; // Start from 0.00001 to 1.49 ETH Price 100000 ETH20 = 1 ETH uint constant STEP_8 = 150000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 0.5 - 2.99 ETH Price 99000 ETH20 = 1 ETH uint constant STEP_7 = 1150000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 1.5 - 19.99 ETH Price 90000 ETH20 = 1 ETH uint constant STEP_6 = 11150000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 11.5 - 199.99 ETH Price 50000 ETH20 = 1 ETH uint constant STEP_5 = 111150000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 111.5 - 1999.99 ETH Price 10000 ETH20 = 1 ETH uint constant STEP_4 = 1111150000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 1111.5 - 19999.99 ETH Price 1000 ETH20 = 1 ETH uint constant STEP_3 = 11111150000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 11111.5 - 199999.99 ETH Price 100 ETH20 = 1 ETH uint constant STEP_2 = 111111150000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 111111.5 - 1999999.99 ETH Price 10 ETH20 = 1 ETH uint constant STEP_1 = 2000000000000 * TOKEN_DECIMAL_MULTIPLIER; // Continue the next 1111111.99 -19999999.99 ETH Price 1 ETH20 = 1 ETH uint constant RATE_9 = 100000 * RATE_SCALE; // Price increases 0 % // Redemption price 98 % Buy back burned uint constant RATE_8 = 99000 * RATE_SCALE; // Price increases 1 % // Redemption price 98 % Buy back burned uint constant RATE_7 = 90000 * RATE_SCALE; // Price increases 10 % // Redemption price 98 % Buy back burned uint constant RATE_6 = 50000 * RATE_SCALE; // Price increases 100 % Increase by 2 times // Redemption price 98 % Buy back burned uint constant RATE_5 = 10000 * RATE_SCALE; // Price increases by 10 times // Redemption price 98 % Buy back burned uint constant RATE_4 = 1000 * RATE_SCALE; // Price Increase by 100 times // Redemption price 98 % Buy back burned uint constant RATE_3 = 100 * RATE_SCALE; // Price increase by 1000 times // Redemption price 98 % Buy back burned uint constant RATE_2 = 10 * RATE_SCALE; // Price increase by 10000 times // Redemption price 98 % Buy back burned uint constant RATE_1 = 1 * RATE_SCALE; // Price increase by 100000 times // Redemption price 98 % Buy back burned uint constant BASE_RATE = 0 * RATE_SCALE; // 1 ETH = 1 ETH20. Standard price 0 % struct ExclusiveRate { // be careful, accuracies this about 1 minutes uint32 workUntil; // exclusive rate or 0 uint rate; // rate bonus percent, which will be divided by 1000 or 0 uint16 bonusPercent1000; // flag to check, that record exists bool exists; } mapping(address => ExclusiveRate) exclusiveRate; function getRateScale() public constant returns (uint) { return RATE_SCALE; } function getBaseRate() public constant returns (uint) { return BASE_RATE; } function getRate(address buyer, uint totalSold, uint amountWei) public constant returns (uint) { uint rate; // apply sale if (totalSold < STEP_9) { rate = RATE_9; } else if (totalSold < STEP_8) { rate = RATE_8; } else if (totalSold < STEP_7) { rate = RATE_7; } else if (totalSold < STEP_6) { rate = RATE_6; } else if (totalSold < STEP_5) { rate = RATE_5; } else if (totalSold < STEP_4) { rate = RATE_4; } else if (totalSold < STEP_3) { rate = RATE_3; } else if (totalSold < STEP_2) { rate = RATE_2; } else if (totalSold < STEP_1) { rate = RATE_1; } else { rate = BASE_RATE; } // apply bonus for amount if (amountWei >= 100000 ether) { rate += rate * 0 / 100; } else if (amountWei >= 10000 ether) { rate += rate * 0 / 100; } else if (amountWei >= 1000 ether) { rate += rate * 0 / 100; } else if (amountWei >= 100 ether) { rate += rate * 0 / 100; } else if (amountWei >= 10 ether) { rate += rate * 0 / 100; } else if (amountWei >= 1 ether) { rate += rate * 0 / 1000; } ExclusiveRate memory eRate = exclusiveRate[buyer]; if (eRate.exists && eRate.workUntil >= now) { if (eRate.rate != 0) { rate = eRate.rate; } rate += rate * eRate.bonusPercent1000 / 1000; } return rate; } function setExclusiveRate(address _investor, uint _rate, uint16 _bonusPercent1000, uint32 _workUntil) onlyOwner { exclusiveRate[_investor] = ExclusiveRate(_workUntil, _rate, _bonusPercent1000, true); } function removeExclusiveRate(address _investor) onlyOwner { delete exclusiveRate[_investor]; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint32 internal startTime; uint32 internal endTime; // address where funds are collected address public wallet; // amount of raised money in wei uint public weiRaised; /** * @dev Amount of already sold tokens. */ uint public soldTokens; /** * @dev Maximum amount of tokens to mint. */ uint internal hardCap; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint value, uint amount); function Crowdsale(uint _startTime, uint _endTime, uint _hardCap, address _wallet) { require(_endTime >= _startTime); require(_wallet != 0x0); require(_hardCap > 0); token = createTokenContract(); startTime = uint32(_startTime); endTime = uint32(_endTime); hardCap = _hardCap; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } /** * @dev this method might be overridden for implementing any sale logic. * @return Actual rate. */ function getRate(uint amount) internal constant returns (uint); function getBaseRate() internal constant returns (uint); /** * @dev rate scale (or divider), to support not integer rates. * @return Rate divider. */ function getRateScale() internal constant returns (uint) { return 1; } // fallback function can be used to buy tokens function() payable { buyTokens(msg.sender, msg.value); } // low level token purchase function function buyTokens(address beneficiary, uint amountWei) internal { require(beneficiary != 0x0); // total minted tokens uint totalSupply = token.totalSupply(); // actual token minting rate (with considering bonuses and discounts) uint actualRate = getRate(amountWei); uint rateScale = getRateScale(); require(validPurchase(amountWei, actualRate, totalSupply)); // calculate token amount to be created uint tokens = amountWei.mul(actualRate).div(rateScale); // update state weiRaised = weiRaised.add(amountWei); soldTokens = soldTokens.add(tokens); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, amountWei, tokens); forwardFunds(amountWei); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds(uint amountWei) internal { wallet.transfer(amountWei); } /** * @dev Check if the specified purchase is valid. * @return true if the transaction can buy tokens */ function validPurchase(uint _amountWei, uint _actualRate, uint _totalSupply) internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = _amountWei != 0; bool hardCapNotReached = _totalSupply <= hardCap; return withinPeriod && nonZeroPurchase && hardCapNotReached; } /** * @dev Because of discount hasEnded might be true, but validPurchase returns false. * @return true if crowdsale event has ended */ function hasEnded() public constant returns (bool) { return now > endTime || token.totalSupply() > hardCap; } /** * @return true if crowdsale event has started */ function hasStarted() public constant returns (bool) { return now >= startTime; } } contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function FinalizableCrowdsale(uint _startTime, uint _endTime, uint _hardCap, address _wallet) Crowdsale(_startTime, _endTime, _hardCap, _wallet) { } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner notFinalized { require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overriden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } modifier notFinalized() { require(!isFinalized); _; } } contract EthereumV2Erc20Crowdsale is usingEthereumV2Erc20Consts, FinalizableCrowdsale { EthereumV2Erc20RateProviderI public rateProvider; function EthereumV2Erc20Crowdsale( uint _startTime, uint _endTime, uint _hardCapTokens ) FinalizableCrowdsale(_startTime, _endTime, _hardCapTokens * TOKEN_DECIMAL_MULTIPLIER, COLD_WALLET) { token.mint(TEAM_ADDRESS, TEAM_TOKENS); token.mint(BOUNTY_ADDRESS, BOUNTY_TOKENS); token.mint(PREICO_ADDRESS, PREICO_TOKENS); EthereumV2Erc20(token).addExcluded(TEAM_ADDRESS); EthereumV2Erc20(token).addExcluded(BOUNTY_ADDRESS); EthereumV2Erc20(token).addExcluded(PREICO_ADDRESS); EthereumV2Erc20RateProvider provider = new EthereumV2Erc20RateProvider(); provider.transferOwnership(owner); rateProvider = provider; } /** * @dev override token creation to integrate with MyWill token. */ function createTokenContract() internal returns (MintableToken) { return new EthereumV2Erc20(); } /** * @dev override getRate to integrate with rate provider. */ function getRate(uint _value) internal constant returns (uint) { return rateProvider.getRate(msg.sender, soldTokens, _value); } function getBaseRate() internal constant returns (uint) { return rateProvider.getRate(msg.sender, soldTokens, MINIMAL_PURCHASE); } /** * @dev override getRateScale to integrate with rate provider. */ function getRateScale() internal constant returns (uint) { return rateProvider.getRateScale(); } /** * @dev Admin can set new rate provider. * @param _rateProviderAddress New rate provider. */ function setRateProvider(address _rateProviderAddress) onlyOwner { require(_rateProviderAddress != 0); rateProvider = EthereumV2Erc20RateProviderI(_rateProviderAddress); } /** * @dev Admin can move end time. * @param _endTime New end time. */ function setEndTime(uint _endTime) onlyOwner notFinalized { require(_endTime > startTime); endTime = uint32(_endTime); } function setHardCap(uint _hardCapTokens) onlyOwner notFinalized { require(_hardCapTokens * TOKEN_DECIMAL_MULTIPLIER > hardCap); hardCap = _hardCapTokens * TOKEN_DECIMAL_MULTIPLIER; } function setStartTime(uint _startTime) onlyOwner notFinalized { require(_startTime < endTime); startTime = uint32(_startTime); } function addExcluded(address _address) onlyOwner notFinalized { EthereumV2Erc20(token).addExcluded(_address); } function validPurchase(uint _amountWei, uint _actualRate, uint _totalSupply) internal constant returns (bool) { if (_amountWei < MINIMAL_PURCHASE) { return false; } return super.validPurchase(_amountWei, _actualRate, _totalSupply); } function finalization() internal { super.finalization(); token.finishMinting(); EthereumV2Erc20(token).crowdsaleFinished(); token.transferOwnership(owner); } } /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // File: contracts/zeppelin/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } contract Token { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract Promotion { mapping(address => address[]) public referrals; // mapping of affiliate address to referral addresses mapping(address => address) public affiliates; // mapping of referrals addresses to affiliate addresses mapping(address => bool) public admins; // mapping of admin accounts string[] public affiliateList; address public owner; function setOwner(address newOwner); function setAdmin(address admin, bool isAdmin) public; function assignReferral (address affiliate, address referral) public; function getAffiliateCount() returns (uint); function getAffiliate(address refferal) public returns (address); function getReferrals(address affiliate) public returns (address[]); } contract TokenList { function isTokenInList(address tokenAddress) public constant returns (bool); } contract BTC20Exchange { function assert(bool assertion) { if (!assertion) throw; } function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } address public owner; mapping (address => uint256) public invalidOrder; event SetOwner(address indexed previousOwner, address indexed newOwner); modifier onlyOwner { assert(msg.sender == owner); _; } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } function getOwner() returns (address out) { return owner; } function invalidateOrdersBefore(address user, uint256 nonce) onlyAdmin { if (nonce < invalidOrder[user]) throw; invalidOrder[user] = nonce; } mapping (address => mapping (address => uint256)) public tokens; //mapping of token addresses to mapping of account balances mapping (address => bool) public admins; mapping (address => uint256) public lastActiveTransaction; mapping (bytes32 => uint256) public orderFills; address public feeAccount; uint256 public feeAffiliate; // percentage times (1 ether) uint256 public inactivityReleasePeriod; mapping (bytes32 => bool) public traded; mapping (bytes32 => bool) public withdrawn; uint256 public makerFee; // fraction * 1 ether uint256 public takerFee; // fraction * 1 ether uint256 public affiliateFee; // fraction as proportion of 1 ether uint256 public makerAffiliateFee; // wei deductible from makerFee uint256 public takerAffiliateFee; // wei deductible form takerFee mapping (address => address) public referrer; // mapping of user addresses to their referrer addresses address public affiliateContract; address public tokenListContract; enum Errors { INVLID_PRICE, // Order prices don't match INVLID_SIGNATURE, // Signature is invalid TOKENS_DONT_MATCH, // Maker/taker tokens don't match ORDER_ALREADY_FILLED, // Order was already filled GAS_TOO_HIGH // Too high gas fee } //event Order(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s); //event Cancel(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade( address takerTokenBuy, uint256 takerAmountBuy, address takerTokenSell, uint256 takerAmountSell, address maker, address indexed taker, uint256 makerFee, uint256 takerFee, uint256 makerAmountTaken, uint256 takerAmountTaken, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash ); event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance, address indexed referrerAddress); event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance, uint256 withdrawFee); event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee, uint256 indexed affiliateFee); //event AffiliateFeeChange(uint256 newAffiliateFee); event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash); event CancelOrder( bytes32 indexed cancelHash, bytes32 indexed orderHash, address indexed user, address tokenSell, uint256 amountSell, uint256 cancelFee ); function setInactivityReleasePeriod(uint256 expiry) onlyAdmin returns (bool success) { if (expiry > 1000000) throw; inactivityReleasePeriod = expiry; return true; } function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, uint256 affiliateFee_, address affiliateContract_, address tokenListContract_) { owner = msg.sender; feeAccount = feeAccount_; inactivityReleasePeriod = 100000; makerFee = makerFee_; takerFee = takerFee_; affiliateFee = affiliateFee_; makerAffiliateFee = safeMul(makerFee, affiliateFee_) / (1 ether); takerAffiliateFee = safeMul(takerFee, affiliateFee_) / (1 ether); affiliateContract = affiliateContract_; tokenListContract = tokenListContract_; } function setFees(uint256 makerFee_, uint256 takerFee_, uint256 affiliateFee_) onlyOwner { require(makerFee_ < 10 finney && takerFee_ < 10 finney); require(affiliateFee_ > affiliateFee); makerFee = makerFee_; takerFee = takerFee_; affiliateFee = affiliateFee_; makerAffiliateFee = safeMul(makerFee, affiliateFee_) / (1 ether); takerAffiliateFee = safeMul(takerFee, affiliateFee_) / (1 ether); FeeChange(makerFee, takerFee, affiliateFee_); } function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } function() external { throw; } function depositToken(address token, uint256 amount, address referrerAddress) { //require(EthermiumTokenList(tokenListContract).isTokenInList(token)); if (referrerAddress == msg.sender) referrerAddress = address(0); if (referrer[msg.sender] == address(0x0)) { if (referrerAddress != address(0x0) && Promotion(affiliateContract).getAffiliate(msg.sender) == address(0)) { referrer[msg.sender] = referrerAddress; Promotion(affiliateContract).assignReferral(referrerAddress, msg.sender); } else { referrer[msg.sender] = Promotion(affiliateContract).getAffiliate(msg.sender); } } tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); lastActiveTransaction[msg.sender] = block.number; if (!Token(token).transferFrom(msg.sender, this, amount)) throw; Deposit(token, msg.sender, amount, tokens[token][msg.sender], referrer[msg.sender]); } function deposit(address referrerAddress) payable { if (referrerAddress == msg.sender) referrerAddress = address(0); if (referrer[msg.sender] == address(0x0)) { if (referrerAddress != address(0x0) && Promotion(affiliateContract).getAffiliate(msg.sender) == address(0)) { referrer[msg.sender] = referrerAddress; Promotion(affiliateContract).assignReferral(referrerAddress, msg.sender); } else { referrer[msg.sender] = Promotion(affiliateContract).getAffiliate(msg.sender); } } tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); lastActiveTransaction[msg.sender] = block.number; Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender], referrer[msg.sender]); } function withdraw(address token, uint256 amount) returns (bool success) { if (safeSub(block.number, lastActiveTransaction[msg.sender]) < inactivityReleasePeriod) throw; if (tokens[token][msg.sender] < amount) throw; tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); if (token == address(0)) { if (!msg.sender.send(amount)) throw; } else { if (!Token(token).transfer(msg.sender, amount)) throw; } Withdraw(token, msg.sender, amount, tokens[token][msg.sender], 0); } function adminWithdraw(address token, uint256 amount, address user, uint256 nonce, uint8 v, bytes32 r, bytes32 s, uint256 feeWithdrawal) onlyAdmin returns (bool success) { bytes32 hash = keccak256(this, token, amount, user, nonce); if (withdrawn[hash]) throw; withdrawn[hash] = true; if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) != user) throw; if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney; if (tokens[token][user] < amount) throw; tokens[token][user] = safeSub(tokens[token][user], amount); tokens[address(0)][user] = safeSub(tokens[address(0x0)][user], feeWithdrawal); //tokens[token][feeAccount] = safeAdd(tokens[token][feeAccount], safeMul(feeWithdrawal, amount) / 1 ether); tokens[address(0)][feeAccount] = safeAdd(tokens[address(0)][feeAccount], feeWithdrawal); //amount = safeMul((1 ether - feeWithdrawal), amount) / 1 ether; if (token == address(0)) { if (!user.send(amount)) throw; } else { if (!Token(token).transfer(user, amount)) throw; } lastActiveTransaction[user] = block.number; Withdraw(token, user, amount, tokens[token][user], feeWithdrawal); } function balanceOf(address token, address user) constant returns (uint256) { return tokens[token][user]; } struct OrderPair { uint256 makerAmountBuy; uint256 makerAmountSell; uint256 makerNonce; uint256 takerAmountBuy; uint256 takerAmountSell; uint256 takerNonce; uint256 takerGasFee; address makerTokenBuy; address makerTokenSell; address maker; address takerTokenBuy; address takerTokenSell; address taker; bytes32 makerOrderHash; bytes32 takerOrderHash; } struct TradeValues { uint256 qty; uint256 invQty; uint256 makerAmountTaken; uint256 takerAmountTaken; address makerReferrer; address takerReferrer; } function trade( uint8[2] v, bytes32[4] rs, uint256[7] tradeValues, address[6] tradeAddresses ) onlyAdmin returns (uint filledTakerTokenAmount) { /* tradeValues [0] makerAmountBuy [1] makerAmountSell [2] makerNonce [3] takerAmountBuy [4] takerAmountSell [5] takerNonce [6] takerGasFee tradeAddresses [0] makerTokenBuy [1] makerTokenSell [2] maker [3] takerTokenBuy [4] takerTokenSell [5] taker */ OrderPair memory t = OrderPair({ makerAmountBuy : tradeValues[0], makerAmountSell : tradeValues[1], makerNonce : tradeValues[2], takerAmountBuy : tradeValues[3], takerAmountSell : tradeValues[4], takerNonce : tradeValues[5], takerGasFee : tradeValues[6], makerTokenBuy : tradeAddresses[0], makerTokenSell : tradeAddresses[1], maker : tradeAddresses[2], takerTokenBuy : tradeAddresses[3], takerTokenSell : tradeAddresses[4], taker : tradeAddresses[5], makerOrderHash : keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]), takerOrderHash : keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5]) }); //bytes32 makerOrderHash = keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]); //bytes32 makerOrderHash = § if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker) { LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } //bytes32 takerOrderHash = keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5]); //bytes32 takerOrderHash = keccak256(this, t.takerTokenBuy, t.takerAmountBuy, t.takerTokenSell, t.takerAmountSell, t.takerNonce, t.taker); if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker) { LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash); return 0; } if (t.makerTokenBuy != t.takerTokenSell || t.makerTokenSell != t.takerTokenBuy) { LogError(uint8(Errors.TOKENS_DONT_MATCH), t.makerOrderHash, t.takerOrderHash); return 0; } // tokens don't match if (t.takerGasFee > 1 finney) { LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash); return 0; } // takerGasFee too high if (!( (t.makerTokenBuy != address(0x0) && safeMul(t.makerAmountSell, 5 finney) / t.makerAmountBuy >= safeMul(t.takerAmountBuy, 5 finney) / t.takerAmountSell) || (t.makerTokenBuy == address(0x0) && safeMul(t.makerAmountBuy, 5 finney) / t.makerAmountSell <= safeMul(t.takerAmountSell, 5 finney) / t.takerAmountBuy) )) { LogError(uint8(Errors.INVLID_PRICE), t.makerOrderHash, t.takerOrderHash); return 0; // prices don't match } TradeValues memory tv = TradeValues({ qty : 0, invQty : 0, makerAmountTaken : 0, takerAmountTaken : 0, makerReferrer : referrer[t.maker], takerReferrer : referrer[t.taker] }); if (tv.makerReferrer == address(0x0)) tv.makerReferrer = feeAccount; if (tv.takerReferrer == address(0x0)) tv.takerReferrer = feeAccount; // maker buy, taker sell if (t.makerTokenBuy != address(0x0)) { tv.qty = min(safeSub(t.makerAmountBuy, orderFills[t.makerOrderHash]), safeSub(t.takerAmountSell, safeMul(orderFills[t.takerOrderHash], t.takerAmountSell) / t.takerAmountBuy)); if (tv.qty == 0) { LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } tv.invQty = safeMul(tv.qty, t.makerAmountSell) / t.makerAmountBuy; tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.invQty); tv.makerAmountTaken = safeSub(tv.qty, safeMul(tv.qty, makerFee) / (1 ether)); tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.qty, makerAffiliateFee) / (1 ether)); tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.qty); tv.takerAmountTaken = safeSub(safeSub(tv.invQty, safeMul(tv.invQty, takerFee) / (1 ether)), safeMul(tv.invQty, t.takerGasFee) / (1 ether)); tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.invQty, takerAffiliateFee) / (1 ether)); tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.qty, safeSub(makerFee, makerAffiliateFee)) / (1 ether)); tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.invQty, safeSub(takerFee, takerAffiliateFee)) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], safeMul(tv.qty, t.takerAmountBuy) / t.takerAmountSell); lastActiveTransaction[t.maker] = block.number; lastActiveTransaction[t.taker] = block.number; Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } // maker sell, taker buy else { tv.qty = min(safeSub(t.makerAmountSell, safeMul(orderFills[t.makerOrderHash], t.makerAmountSell) / t.makerAmountBuy), safeSub(t.takerAmountBuy, orderFills[t.takerOrderHash])); if (tv.qty == 0) { LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash); return 0; } tv.invQty = safeMul(tv.qty, t.makerAmountBuy) / t.makerAmountSell; tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.qty); tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.invQty, makerAffiliateFee) / (1 ether)); tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.invQty); tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.qty, takerAffiliateFee) / (1 ether)); tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, safeSub(makerFee, makerAffiliateFee)) / (1 ether)); tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, safeSub(takerFee, takerAffiliateFee)) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.invQty); orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); //safeMul(qty, tradeValues[takerAmountBuy]) / tradeValues[takerAmountSell]); lastActiveTransaction[t.maker] = block.number; lastActiveTransaction[t.taker] = block.number; Trade( t.takerTokenBuy, tv.qty, t.takerTokenSell, tv.invQty, t.maker, t.taker, makerFee, takerFee, tv.makerAmountTaken , tv.takerAmountTaken, t.makerOrderHash, t.takerOrderHash ); return tv.qty; } } function batchOrderTrade( uint8[2][] v, bytes32[4][] rs, uint256[7][] tradeValues, address[6][] tradeAddresses ) { for (uint i = 0; i < tradeAddresses.length; i++) { trade( v[i], rs[i], tradeValues[i], tradeAddresses[i] ); } } function cancelOrder( /* [0] orderV [1] cancelV */ uint8[2] v, /* [0] orderR [1] orderS [2] cancelR [3] cancelS */ bytes32[4] rs, /* [0] orderAmountBuy [1] orderAmountSell [2] orderNonce [3] cancelNonce [4] cancelFee */ uint256[5] cancelValues, /* [0] orderTokenBuy [1] orderTokenSell [2] orderUser [3] cancelUser */ address[4] cancelAddresses ) public onlyAdmin { // Order values should be valid and signed by order owner bytes32 orderHash = keccak256( this, cancelAddresses[0], cancelValues[0], cancelAddresses[1], cancelValues[1], cancelValues[2], cancelAddresses[2] ); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == cancelAddresses[2]); // Cancel action should be signed by cancel's initiator bytes32 cancelHash = keccak256(this, orderHash, cancelAddresses[3], cancelValues[3]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", cancelHash), v[1], rs[2], rs[3]) == cancelAddresses[3]); // Order owner should be same as cancel's initiator require(cancelAddresses[2] == cancelAddresses[3]); // Do not allow to cancel already canceled or filled orders require(orderFills[orderHash] != cancelValues[0]); // Limit cancel fee if (cancelValues[4] > 6 finney) { cancelValues[4] = 6 finney; } // Take cancel fee // This operation throw an error if fee amount is more than user balance tokens[address(0)][cancelAddresses[3]] = safeSub(tokens[address(0)][cancelAddresses[3]], cancelValues[4]); // Cancel order by filling it with amount buy value orderFills[orderHash] = cancelValues[0]; // Emit cancel order CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]); } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } } /** * @title Token * @dev Token interface necessary for working with tokens within the exchange contract. */ contract IToken { /// @return total amount of tokens function totalSupply() public constant returns (uint256 supply); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public 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) 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 `_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) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); uint public decimals; string public name; } pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library LSafeMath { uint256 constant WAD = 1 ether; function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a == b) return c; revert(); } function div(uint256 a, uint256 b) internal pure returns (uint256) { if (b > 0) { uint256 c = a / b; return c; } revert(); } function sub(uint256 a, uint256 b) internal pure returns (uint256) { if (b <= a) return a - b; revert(); } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c >= a) return c; revert(); } function wmul(uint a, uint b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function wdiv(uint a, uint b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } } /** * @title Coinchangex * @dev This is the main contract for the Coinchangex exchange. */ contract Tokenchange { using LSafeMath for uint; struct SpecialTokenBalanceFeeTake { bool exist; address token; uint256 balance; uint256 feeTake; } uint constant private MAX_SPECIALS = 10; /// Variables address public admin; // the admin address address public feeAccount; // the account that will receive fees uint public feeTake; // percentage times (1 ether) bool private depositingTokenFlag; // True when Token.transferFrom is being called from depositToken mapping (address => mapping (address => uint)) public tokens; // mapping of token addresses to mapping of account balances (token=0 means Ether) mapping (address => mapping (bytes32 => uint)) public orderFills; // mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) SpecialTokenBalanceFeeTake[] public specialFees; /// Logging Events event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); /// This is a modifier for functions to check if the sending user address is the same as the admin user address. modifier isAdmin() { require(msg.sender == admin); _; } /// Constructor function. This is only called on contract creation. function Coinchangex(address admin_, address feeAccount_, uint feeTake_) public { admin = admin_; feeAccount = feeAccount_; feeTake = feeTake_; depositingTokenFlag = false; } /// The fallback function. Ether transfered into the contract is not accepted. function() public { revert(); } /// Changes the official admin user address. Accepts Ethereum address. function changeAdmin(address admin_) public isAdmin { require(admin_ != address(0)); admin = admin_; } /// Changes the account address that receives trading fees. Accepts Ethereum address. function changeFeeAccount(address feeAccount_) public isAdmin { feeAccount = feeAccount_; } /// Changes the fee on takes. Can only be changed to a value less than it is currently set at. function changeFeeTake(uint feeTake_) public isAdmin { // require(feeTake_ <= feeTake); feeTake = feeTake_; } // add special promotion fee function addSpecialFeeTake(address token, uint256 balance, uint256 feeTake) public isAdmin { uint id = specialFees.push(SpecialTokenBalanceFeeTake( true, token, balance, feeTake )); } // chnage special promotion fee function chnageSpecialFeeTake(uint id, address token, uint256 balance, uint256 feeTake) public isAdmin { require(id < specialFees.length); specialFees[id] = SpecialTokenBalanceFeeTake( true, token, balance, feeTake ); } // remove special promotion fee function removeSpecialFeeTake(uint id) public isAdmin { if (id >= specialFees.length) revert(); uint last = specialFees.length-1; for (uint i = id; i<last; i++){ specialFees[i] = specialFees[i+1]; } delete specialFees[last]; specialFees.length--; } //return total count promotion fees function TotalSpecialFeeTakes() public constant returns(uint) { return specialFees.length; } //////////////////////////////////////////////////////////////////////////////// // Deposits, Withdrawals, Balances //////////////////////////////////////////////////////////////////////////////// /** * This function handles deposits of Ether into the contract. * Emits a Deposit event. * Note: With the payable modifier, this function accepts Ether. */ function deposit() public payable { tokens[0][msg.sender] = tokens[0][msg.sender].add(msg.value); Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); } /** * This function handles withdrawals of Ether from the contract. * Verifies that the user has enough funds to cover the withdrawal. * Emits a Withdraw event. * @param amount uint of the amount of Ether the user wishes to withdraw */ function withdraw(uint amount) public { require(tokens[0][msg.sender] >= amount); tokens[0][msg.sender] = tokens[0][msg.sender].sub(amount); msg.sender.transfer(amount); Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); } /** * This function handles deposits of Ethereum based tokens to the contract. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Emits a Deposit event. * Note: Remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. * @param token Ethereum contract address of the token or 0 for Ether * @param amount uint of the amount of the token the user wishes to deposit */ function depositToken(address token, uint amount) public { require(token != 0); depositingTokenFlag = true; require(IToken(token).transferFrom(msg.sender, this, amount)); depositingTokenFlag = false; tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); Deposit(token, msg.sender, amount, tokens[token][msg.sender]); } /** * This function provides a fallback solution as outlined in ERC223. * If tokens are deposited through depositToken(), the transaction will continue. * If tokens are sent directly to this contract, the transaction is reverted. * @param sender Ethereum address of the sender of the token * @param amount amount of the incoming tokens * @param data attached data similar to msg.data of Ether transactions */ function tokenFallback( address sender, uint amount, bytes data) public returns (bool ok) { if (depositingTokenFlag) { // Transfer was initiated from depositToken(). User token balance will be updated there. return true; } else { // Direct ECR223 Token.transfer into this contract not allowed, to keep it consistent // with direct transfers of ECR20 and ETH. revert(); } } /** * This function handles withdrawals of Ethereum based tokens from the contract. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Emits a Withdraw event. * @param token Ethereum contract address of the token or 0 for Ether * @param amount uint of the amount of the token the user wishes to withdraw */ function withdrawToken(address token, uint amount) public { require(token != 0); require(tokens[token][msg.sender] >= amount); tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount); require(IToken(token).transfer(msg.sender, amount)); Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); } /** * Retrieves the balance of a token based on a user address and token address. * @param token Ethereum contract address of the token or 0 for Ether * @param user Ethereum address of the user * @return the amount of tokens on the exchange for a given user address */ function balanceOf(address token, address user) public constant returns (uint) { return tokens[token][user]; } //////////////////////////////////////////////////////////////////////////////// // Trading //////////////////////////////////////////////////////////////////////////////// /** * Facilitates a trade from one user to another. * Requires that the transaction is signed properly, the trade isn't past its expiration, and all funds are present to fill the trade. * Calls tradeBalances(). * Updates orderFills with the amount traded. * Emits a Trade event. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @param amount uint amount in terms of tokenGet that will be "buy" in the trade */ function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require(( (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user) && block.number <= expires && orderFills[user][hash].add(amount) <= amountGet )); tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); orderFills[user][hash] = orderFills[user][hash].add(amount); Trade(tokenGet, amount, tokenGive, amountGive.mul(amount) / amountGet, user, msg.sender); } /** * This is a private function and is only being called from trade(). * Handles the movement of funds when a trade occurs. * Takes fees. * Updates token balances for both buyer and seller. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param user Ethereum address of the user who placed the order * @param amount uint amount in terms of tokenGet that will be "buy" in the trade */ function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { uint256 feeTakeXfer = calculateFee(amount); tokens[tokenGet][msg.sender] = tokens[tokenGet][msg.sender].sub(amount.add(feeTakeXfer)); tokens[tokenGet][user] = tokens[tokenGet][user].add(amount); tokens[tokenGet][feeAccount] = tokens[tokenGet][feeAccount].add(feeTakeXfer); tokens[tokenGive][user] = tokens[tokenGive][user].sub(amountGive.mul(amount).div(amountGet)); tokens[tokenGive][msg.sender] = tokens[tokenGive][msg.sender].add(amountGive.mul(amount).div(amountGet)); } //calculate fee including special promotions function calculateFee(uint amount) private constant returns(uint256) { uint256 feeTakeXfer = 0; uint length = specialFees.length; bool applied = false; for(uint i = 0; length > 0 && i < length; i++) { SpecialTokenBalanceFeeTake memory special = specialFees[i]; if(special.exist && special.balance <= tokens[special.token][msg.sender]) { applied = true; feeTakeXfer = amount.mul(special.feeTake).div(1 ether); break; } if(i >= MAX_SPECIALS) break; } if(!applied) feeTakeXfer = amount.mul(feeTake).div(1 ether); return feeTakeXfer; } /** * This function is to test if a trade would go through. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @param amount uint amount in terms of tokenGet that will be "buy" in the trade * @param sender Ethereum address of the user taking the order * @return bool: true if the trade would be successful, false otherwise */ function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public constant returns(bool) { if (!( tokens[tokenGet][sender] >= amount && availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount )) { return false; } else { return true; } } /** * This function checks the available volume for a given order. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @return uint: amount of volume available for the given order in terms of amountGet / tokenGet */ function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns(uint) { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); if (!( (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user) && block.number <= expires )) { return 0; } uint[2] memory available; available[0] = amountGet.sub(orderFills[user][hash]); available[1] = tokens[tokenGive][user].mul(amountGet) / amountGive; if (available[0] < available[1]) { return available[0]; } else { return available[1]; } } /** * This function checks the amount of an order that has already been filled. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet */ function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns(uint) { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); return orderFills[user][hash]; } /** * This function cancels a given order by editing its fill data to the full amount. * Requires that the transaction is signed properly. * Updates orderFills to the full amountGet * Emits a Cancel event. * Note: tokenGet & tokenGive can be the Ethereum contract address. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet */ function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public { bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require ((ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == msg.sender)); orderFills[msg.sender][hash] = amountGet; Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s); } /** * This function handles deposits of Ether into the contract, but allows specification of a user. * Note: This is generally used in migration of funds. * Note: With the payable modifier, this function accepts Ether. */ function depositForUser(address user) public payable { require(user != address(0)); require(msg.value > 0); tokens[0][user] = tokens[0][user].add(msg.value); } /** * This function handles deposits of Ethereum based tokens into the contract, but allows specification of a user. * Does not allow Ether. * If token transfer fails, transaction is reverted and remaining gas is refunded. * Note: This is generally used in migration of funds. * Note: Remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. * @param token Ethereum contract address of the token * @param amount uint of the amount of the token the user wishes to deposit */ function depositTokenForUser(address token, uint amount, address user) public { require(token != address(0)); require(user != address(0)); require(amount > 0); depositingTokenFlag = true; require(IToken(token).transferFrom(msg.sender, this, amount)); depositingTokenFlag = false; tokens[token][user] = tokens[token][user].add(amount); } }
* @dev this method might be overridden for implementing any sale logic. @return Actual rate./* @dev rate scale (or divider), to support not integer rates. @return Rate divider./
function getRate(uint amount) internal constant returns (uint); function getBaseRate() internal constant returns (uint); function getRateScale() internal constant returns (uint) { return 1; }
971,905
[ 1, 2211, 707, 4825, 506, 11000, 364, 19981, 1281, 272, 5349, 4058, 18, 327, 23788, 4993, 18, 19, 225, 4993, 3159, 261, 280, 21713, 3631, 358, 2865, 486, 3571, 17544, 18, 327, 13025, 21713, 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, 4170, 340, 12, 11890, 3844, 13, 2713, 5381, 1135, 261, 11890, 1769, 203, 203, 565, 445, 8297, 4727, 1435, 2713, 5381, 1135, 261, 11890, 1769, 203, 203, 565, 445, 4170, 340, 5587, 1435, 2713, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 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, -100, -100, -100, -100, -100, -100, -100 ]